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

Property inheritance involving objects and prototypes

我是 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

如您所见,在添加 returns 后打印 doSomethingprop 属性 another value,但访问 [=16] =]的propreturnsundefined.

难道 anotherInstance 不应该 "inherit" 这样 prop 属性 因为它是在创建它的函数中定义的吗?

提前致谢。

向函数添加 属性 与向函数的原型对象添加 属性 不同。函数的实例继承了函数的 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只是一个属性的函数,对原型继承没有任何作用