用于功能的自定义原型链

时间:2012-05-15 09:03:25

标签: javascript prototype ecmascript-5

我只是好奇我是否可以将一个对象包含到函数原型链中。我的意思是:

var test = function() { return 'a'; };

console.log(test.bind(this)); // return new bound function

// changing the prototype
// in console the prototype is really set as needed
// test => new object => function prototype => Object prototype
var F = function() {};
F.prototype = Function.prototype;
test.prototype = new F();

console.log(test.bind()); // this still works and returns new bound function

test.prototype.bind = function() {
    return 'test';
};

console.log(test.bind()); // this does not work as expected -> returns new bound function instead of 'test'. When I do delete Function.prototype.bind, then console.log(test.bind) returns undefined

1 个答案:

答案 0 :(得分:2)

你有一个功能test。它是instanceof Function,并且继承自Function.prototype,因此您可以拨打test.bind

然后将函数的“prototype”属性设置为继承自Function.prototype的对象。这意味着test的所有实例都将从该对象(以及Function.prototype)继承:

var t = new test;
t instanceof test; // => true
t instanceof Function; // => true

然后覆盖自定义原型对象上的test属性。你这样做很好,因为只应在函数(即可调用对象)上调用Function方法:

>>> Function.prototype.bind.call({})
Unhandled Error: Function.prototype.bind: this object not callable

在使用console.log的测试中,您只在test函数上应用函数方法,而不是在它的实例上。好,因为他们失败了。所以,我看不出任何对象应该从Function继承的原因 - 你不能构造不直接从Function继承的函数。

相关问题