【发布时间】:2018-11-21 08:05:37
【问题描述】:
我是 JS 的新手,在我的一个测试中,我一直试图弄清楚以下代码在属性继承方面是如何工作的。
function doSomething(){}
doSomething.prototype.foo = "bar"; //Add "foo" property to doSomething's prototype
let anInstance = new doSomething();
anInstance.prop = "value"; //Add "prop" property to object "anInstance"
doSomething.prop = "another value"; //Add "prop" property to "doSomething"
let anotherInstance = new doSomething();
console.log(doSomething.prop);
console.log(anInstance);
console.log(anotherInstance.prop);
这是上面脚本在控制台中的输出:
another value
doSomething{prop: "value"}
prop: "value"
__proto__:
foo: "bar"
constructor: ƒ doSomething()
__proto__: Object
undefined
如您所见,将doSomething 的prop 属性添加到其中后打印会返回预期的another value,但访问anotherInstance 的prop 会返回undefined。
anotherInstance 不是应该“继承”此类 prop 属性,因为它是在创建它的函数中定义的吗?
提前致谢。
【问题讨论】:
标签: javascript inheritance properties prototype