继承和原型链在 JS 中是如何工作的

How inheritance and Prototype Chain works in JS

看看我的代码。我不明白它是如何工作的

function doSomething() {
  this.testProp = 'testProp';
}

doSomething.testProp1 = "testProp1";
var doSomeInstancing = new doSomething();

console.log("doSomething.testProp:" + doSomething.testProp);
//undefined
console.log("doSomething.testProp1:" + doSomething.testProp1);
//testProp1
console.log(doSomething.hasOwnProperty('testProp1'));
//true 

console.log("doSomeInstancing.testProp:" + doSomeInstancing.testProp);
//testProp
console.log("doSomeInstancing.testProp1:" + doSomeInstancing.testProp1);
//undefined   
console.log(doSomeInstancing.hasOwnProperty('testProp1'));
//false

问题是为什么 testProp 在 doSomething 中未定义,而在 doSomeInstancing 中未定义,反之亦然。

您在这里处理两个不同的对象:

函数:doSomething 对象:doSomeInstancing

两者都是对象,都可以有属性。 doSomeInstancing 是当您调用 new doSomething() 时从函数返回的对象,它是 this 在函数体中引用的对象。向该对象添加属性不会影响另一个对象,即 doSomething 函数。反之亦然。

如果您试图继承一个 属性,您实际上是在寻找第三个对象:doSomething.prototype。这是一个 属性 函数,指向实例将链接到的对象。 doSomeInstancing 将从这个对象继承到原型链中。例如:

function doSomething() {
  this.testProp = 'testProp';
}

doSomething.prototype.testProp1 = "testProp1 value"

let p = new doSomething()

// p's parent in the protoype chain is doSomething.prototype
console.log(Object.getPrototypeOf(p) === doSomething.prototype)

console.log(p.testProp)
console.log(p.testProp1)