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



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

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") );

结果是

比;未定义,未定义,function(),未定义

比;"Unicorn"

比;TypeError: d.test不是一个函数

虽然它本身不是"继承",但实现这一点的方法是创建一个b.test函数来运行a.test;

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

我们可以创建一个虚拟构造器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

如何简单地分配该函数?

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

最新更新