我只是好奇我是否可以将一个对象包含到函数原型(prototype)链中。我的意思是:
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
最佳答案
你有一个函数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
然后您覆盖自定义原型(prototype)对象上的测试属性。这样做很好,因为 Function 方法只应在函数(即可调用对象)上调用:
>>> Function.prototype.bind.call({})
Unhandled Error: Function.prototype.bind: this object not callable
在使用 console.log
进行的测试中,您仅将 Function 方法应用于 test
函数,而不是它的实例。很好,因为他们会失败。所以,我看不出任何对象应该从 Function
继承的原因 - 你不能构造不直接从 Function
继承的函数。
关于javascript - 函数的自定义原型(prototype)链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10597421/