任何对象都有__proto__
,只有函数对象才有prototype
,prototype.constructor指回自己,函数被当作构造函数创建实例时它的prototype将作为实例的__proto__
。在定义prototype是显示的将constructor指向函数自己,否则constructor将指向Object,通过constructor已经无法确定对象的类型了。还有显示定义了constructor后在对象实例中是可枚举的。
function feed() { this.a = 'hello'; } feed.a = 'word'; var f = new feed(); console.log(f.a); // 输出 'hello' console.log(f.__proto__.a); // 输出 undefined console.log(f.__proto__.constructor.a); // 输出 'word'
```
function feed() {
this.a = 'hello';
}
feed.prototype = {
b: 'www',
};
console.log(feed.prototype.constructor); // 输出 ƒunction Object() { [native code] }
feed.prototype = {
constructor: feed,
b: 'www',
};
console.log(feed.prototype.constructor); // 输出 ƒunction feed() { this.a = 'hello'; }
var f = new feed();
for(var key in f) {
console.log(key); // 依次输出 a、constructor、b
}
```
网友评论