你如何在javascript中继承单个函数?

时间:2015-07-19 21:23:10

标签: javascript prototypal-inheritance

我知道如果它是原型,你可以如何扩展一个完整的对象。但是也可以扩展单个函数吗?

var a = function(){}
a.prototype.test = function( p ){
    return p
}

var b = function(){};
b.prototype.test = Object.create(a.prototype.test);

var c = new a();
var d = new b();
console.log(typeof a.test, typeof b.test, typeof c.test, typeof d.test)

console.log( c.test("Unicorn") );
console.log( d.test("Unicorn") );

这导致

  

> undefined,undefined,function(),undefined

     

> “独角兽”

     

> TypeError:d.test不是函数

3 个答案:

答案 0 :(得分:2)

虽然它本身不是“继承”,但是这样做的方法是创建一个运行a.test的b.test函数;

b.prototype.test = function () {
    return a.prototype.test.apply(this, arguments);
};

答案 1 :(得分:1)

我们可以创建一个虚拟构造函数x并使用test扩展其原型。

var a = function(){}
a.prototype.test = function( p ){
    return p
}

var b = function(){};
var x = function(){};
x.prototype.test = a.prototype.test
b.prototype = new x();

var c = new a();
var d = new b();
console.log(typeof a.test, typeof b.test, typeof c.test, typeof d.test)

console.log( c.test("Unicorn") );
console.log( d.test("Unicorn") );

我认为更简单的方法是b.prototype.test = a.prototype.test

答案 2 :(得分:1)

如何简单地分配该功能?

b.prototype.test = a.prototype.test;