这也是一个很好的继承模式吗?我从未在 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"