Javascript:将方法添加到父类/要继承

时间:2015-07-25 18:18:57

标签: javascript object

我想在父类A中添加一个方法“bar”,在定义子类B之后,以便继承该方法。有可能吗?

我尝试了以下代码

function A() {
   this.foo = function () {
       console.log('foo')
   }
}
function B() {
   A.call(this)
}

// (trying to) add a new method to A

A.prototype.bar = function () {
    console.log('bar');
}

// It works with instances of A
var a = new A()     
a.foo()            // ok
a.bar()            // ok

// but not with an instance of B
var b = new B()     
b.foo()            // this works
b.bar()            // not this one <------

/*  
   Exception: b.bar is not a function
   @Scratchpad/3:17:1
*/

有任何建议吗?

4 个答案:

答案 0 :(得分:1)

如果您只需修改代码,可以链接如下方法:

function B() {
   A.call(this)
   for(var i in A.prototype){ this[i] = A.prototype[i]; }
}

但我认为这是不好的方式。

答案 1 :(得分:1)

function A() {
   this.foo = function () {
       console.log('foo');
   };
}
function B() {
   A.call(this);
}

// (trying to) add a new method to A

A.prototype.bar = function () {
    console.log('bar');
};
B.prototype = Object.create(A.prototype);
// It works with instances of A
var a = new A()  ;   
a.foo()  ;          // ok
a.bar()  ;          // ok

// but not with an instance of B
var b = new B() ;    
b.foo()   ;         // this works
b.bar()  ;

我的继承功能类型的情况 - 你不能添加类中不存在的方法。使用原型

答案 2 :(得分:1)

// if you define the prototype as an object
var A = {
    foo: function() {
        console.log('foo');
    }
};

// and define constructors using Object.create
function newA() {
   return Object.create(A);
};

function newB() {
    return Object.create(newA());   
};

// you can add methods to the prototype
A.bar = function () {
    console.log('bar');
};

// it works with instances of A
var a = newA()     
a.foo();
a.bar();

// and instances of B
var b = newB();  
b.foo();
b.bar();

// you can even modify the prototype after the fact
A.baz = function() {
    console.log('baz');   
};

// and that will work as well
a.baz();
b.baz();

http://jsfiddle.net/5s8ahvLq/

如果您不希望后者能够在事后编辑原型,请使用Object.assign或提供该功能的下划线或lodash:

function newA() {
    return Object.create(Object.assign({}, A));
}

答案 3 :(得分:0)

你错过了:

B.prototype.__proto__ = A.prototype

如果您不喜欢使用__proto__,可以使用:

B.prototype = Object.create(A.prototype);