JavaScript:ECMAScript5 中的继承

标签 javascript oop inheritance

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/

相关文章:

java - 当实现仅在一个方法上不同时,建议使用哪种设计模式?

c++ - virtual void funcFoo() const = 0 和 virtual void funcFoo() = 0; 之间的区别

javascript - Javascript 中最后计算的表达式

Python 'str' 对象在使用函数变量调用类实例时没有属性 'name'

javascript - 重新格式化来自 2 个数组的数据并包含计数

java - 在传递给 JFrame 的 java 控件上显示滚动条?

Javascript OOP 回调 "this"应用

inheritance - Jasmine + 测试继承的方法已被调用

javascript - RxJS 5.4.3 中的 .ofArrayChanges() 替代方案

javascript - 在每次执行时增加 setInterval 计时器