美文网首页
prototype基础

prototype基础

作者: zhulichao | 来源:发表于2020-07-24 09:04 被阅读0次

任何对象都有__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
}
```

相关文章

网友评论

      本文标题:prototype基础

      本文链接:https://www.haomeiwen.com/subject/ydxjhktx.html