var A = function () {
this.p1 = 2;
};
A.prototype.f1 = function () {
return 7;
};
var B = function () {
inherit(A, B);
};
function inherit(Child, Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
}
var b = new B();
console.log(b.p1); // get undefined here
我是 JS 新手,抱歉转储问题。我想从 A
继承 B
。我究竟做错了什么?
最佳答案
您仅在创建 B
实例后调用 inherit()
。
在定义这两个函数后,您需要静态调用一次inherit()
。
您还需要在 B
中的实例上调用 A
。
有关如何正确进行继承的更多详细信息,请参阅 my blog .
关于JavaScript:ECMAScript5 中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40330473/