涉及对象和原型的属性继承

时间:2018-11-21 08:05:37

标签: javascript object properties prototype

我是JS的新手,在我的一项测试中,我一直试图弄清楚以下代码在属性继承方面的工作方式。

select '0.28'*100;

这是上面脚本在控制台中的输出:

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 的{​​{1}}属性添加到其中后,将返回预期的doSomething,但访问prop的{​​{1}}则会返回another value

anotherInstance是否应该“继承”这样的prop属性,因为它是在创建它的函数中定义的?

谢谢。

1 个答案:

答案 0 :(得分:1)

向函数添加属性与向函数的原型对象添加属性不同。函数实例继承函数的prototype属性,而不继承函数自身的属性:

function doSomething(){}

doSomething.prototype.foo = "bar"; //Add "foo" property to doSomething's prototype

doSomething.prop = "another value"; //Add "prop" property to "doSomething" but no the prototype

let anotherInstance = new doSomething();

// only has foo:
console.log(doSomething.prototype)

// this is the object it will inherit from
// only has foo
console.log(Object.getPrototypeOf(anotherInstance))

//they are the same object:
console.log(doSomething.prototype === Object.getPrototypeOf(anotherInstance))

doSomething.prop以上的代码中,该函数只是该函数的一个属性,它在原型继承中不起作用。