【发布时间】:2019-01-30 12:57:45
【问题描述】:
【问题讨论】:
-
请将代码发布为文本,而不是图片。
标签: javascript prototypal-inheritance proto
【问题讨论】:
标签: javascript prototypal-inheritance proto
当您键入 p.constructor.prototype.a 时,JavaScript 会检查对象本身中的属性 constructor,但它没有。当这种情况发生时,它会通过__proto__ 遍历原型链。这里的问题是对象p 及其原型没有属性constructor。这是由使用Object.create() 引起的。它与new 之间的区别已经在Understanding the difference between Object.create() and new SomeFunction() 中进行了描述,@adiga 在您的帖子下评论:)
【讨论】:
这很简单。
new a is Object.create(a.prototype)
虽然 Object.create(a) 与 Object.create(a.prototype) 不同。 new 运行构造函数代码,而 object 不运行构造函数。
参见以下示例:
function a(){
this.b = 'xyz';
};
a.prototype.c = 'test';
var x = new a();
var y = Object.create(a);
//Using New Keyword
console.log(x); //Output is object
console.log(x.b); //Output is xyz.
console.log(x.c); //Output is test.
//Using Object.create()
console.log(y); //Output is function
console.log(y.b); //Output is undefined
console.log(y.c); //Output is undefined
【讨论】: