属性列举与原型的关系
自订原型 与 原生原型 最大的不同是在可列举(enumerable)的部分
原生原型enumberable : false;
自订原型enumberable : true;
这里举一个例子
function person(){
}
person.prototype.name = '小明';
var alex = new person();
alex.a = undefined;
console.log(alex);
会发现 person 原型的 name属性颜色
与物件原型的属性颜色不一样
但它跟我们一般定义属性的颜色是一样的
那为什麽都是原型属性 为什麽颜色会不一样呢??
我们继续往下看
// 利用for in 来查看
for(var key in alex){
console.log(key); // a name
}
// 会发现原型的 name 出现,但为什麽原型其他属性不会被列举呢??
因为这时候的 name 的 enumerable 为true
我们利用 getOwnPropertyDescriptor 来证明
function person(){
}
person.prototype.name = '小明';
var alex = new person();
alex.a = undefined;
for(var key in alex){
console.log(key); // a name
}
console.log(Object.getOwnPropertyDescriptor(alex,'a')); // enumerable: true
console.log(Object.getOwnPropertyDescriptor(alex.__proto__,'name')); // enumerable: true
console.log(Object.getOwnPropertyDescriptor(alex.__proto__.__proto__,'toString')); // enumerable: false
所以假如我们把 name 的 enumerable改为false
function person(){
}
person.prototype.name = '小明';
Object.defineProperty(person.prototype,'name',{
enumerable: false,
})
var alex = new person();
alex.a = undefined;
console.log(alex);
for(var key in alex){
console.log(key); // a
}
console.log(Object.getOwnPropertyDescriptor(alex,'a')); // enumerable: true
console.log(Object.getOwnPropertyDescriptor(alex.__proto__,'name')); // enumerable: false
console.log(Object.getOwnPropertyDescriptor(alex.__proto__.__proto__,'toString')); // enumerable: false
这样列举的东西 只有 a而已
name 无法被列举
那今天的介绍就到这里
若有任何问题 或 内容有误
都可以跟我说唷
>>: [Golang]同步工具-sync包的Wait、Signal、Broadcast方法说明-心智图总结
新增表格 add_table() rows:列数 cols:栏数 doc = docx.Docume...
「从架构的角度来看,资料库是一个非实体 — 它与软件系统架构之间的关系就像门把与你家的架构那样」 ...
到目前为止,我们有了时间,可以输入,还可以对「物件」进行位移,看来可以开始让「小铁(LittleIr...
在 Boxenn::UseCase 中处理 validation? dry-monads 中有提供 ...
看完这篇文章你会得到的成果图 (没有,今天不写程序,但要讲重要观念XD) PyQt 的程序逻辑 我特...