版权声明:本文为吴孔云博客原创文章,转载请注明出处并带上链接,谢谢。 https://cloud.tencent.com/developer/article/1347616
function Animal(){}
function Dog (age){
this.name = 'fuck you' ;
this.age = age
}
var dog = new Dog(12);
console.log(dog); //{name: "fuck you", age: 12}
Dog.prototype = Animal;
var dog2 = new Dog(12);
console.log(dog2);//{age: 12}
dog2对象的name属性不见了,why?
在segmentfault社区找到相关概念:
当为一个对象属性赋值是要遵循以下规则:
Object.getOwnPropertyNames(Animal)
//["length", "name", "arguments", "caller", "prototype"]
//Animal有上述5个属性
Object.getOwnPropertyDescriptor(Animal, 'name')
//Object {value: "Animal", writable: false, enumerable: false, configurable: true}
//属性'name'只读,所以再次赋值无效
//通过知道属性只读,对象属性赋值操作无效,那么我们可以更改name的property-wirteable为true,如下
Object.defineProperty(Animal, 'name', {writable: true})
Object.getOwnPropertyDescriptor(Animal, 'name')
//Object {value: "Animal", writable: true, enumerable: false, configurable: true}
var dog3 = new Dog(13)
//Dog {name: "fuck you", age: 13}
//属性enumerable都为false,所以for in遍历不出来
Object.keys(Animal) //[]
//用ES6的Reflect
Reflect.ownKeys(Animal)
//["length", "name", "arguments", "caller", "prototype"]
Reflect.has(Animal,'name') //true
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有