JavaScript:ECMAScript5中的继承

时间:2016-10-30 15:10:15

标签: 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新手,抱歉转储问题。我想从B继承A。我究竟做错了什么?

3 个答案:

答案 0 :(得分:2)

您只需在创建inherit()实例后调用B

在定义两个函数后,您需要静态调用inherit()

您还需要在A上的实例上致电B

有关如何正确执行继承的更多详细信息,请参阅my blog

答案 1 :(得分:1)

  

我做错了什么?

两件事:

  1. 您在 inherit内呼叫B 。你应该在外面做。

  2. B内,您应该拨打A,例如

    A.call(this/*, other, args, here, if, needed*/);
    

    A.apply(this, arguments);
    

    通过自动B伪数组传递在运行时收到的所有参数arguments

  3. 像这样:

    
    
    var A = function () {
        this.p1 = 2;
    };
    A.prototype.f1 = function () {
        return 7;
    };
    var B = function () {
        A.call(this);        // <==== Added
    };
    inherit(A, B);           // <==== Moved
    
    function inherit(Child, Parent) {
        Child.prototype = Object.create(Parent.prototype);
        Child.prototype.constructor = Child;
    }
    
    var b = new B();
    console.log(b.p1); // get 2 here now
    &#13;
    &#13;
    &#13;

答案 2 :(得分:1)

您没有调用基础构造函数。此外,如果只继承一次类,那就足够了。

&#13;
&#13;
var A = function () {
    this.p1 = 2;
};
A.prototype.f1 = function () {
    return 7;
};
var B = function () {
    A.apply(this, arguments);
};
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 
&#13;
&#13;
&#13;