在 JavaScript 中通过 B.prototype = new A() 继承,为什么需要设置 B.prototyp

In JavaScript inheritance via B.prototype = new A() why does one need to set B.prototype.constructor = B?

本文关键字:为什么 继承 prototyp 设置 JavaScript prototype new      更新时间:2023-09-26

这也是一个很好的继承模式吗?我从未在 JavaScript 继承教程中看到过它的讨论,但有时在实际代码中使用。您能指出与其他模式相比的缺点和/或优势吗?

因为构造函数现在指向"A"的构造函数(原型属性)所以我们希望它指向 B()

B.prototype.constructor 是一个指向原始构造函数的指针,当我们更改 B 的原型时 ( B.prototype = new A() ) 时,B.prototype.constructor 会丢失对实际 A() 的引用,并引用/指向 B()。注意 新的 A() 仍将调用默认构造函数。

这里唯一的目的就是将其改回 B() ( B.prototype.constructor=B ) 可以是,当将来出于某种目的调用带有原型(如 B.prototype.constructor()B.prototype.constructor.call())的构造函数时,它不指向 A()

function A(){
console.log("A")
}
function B(){
console.log("B")
}

B.prototype = Object.create(A.prototype);
new B() // Still console.logs "B"
 B.prototype.constructor() // console.logs "A"