功能的定制原型链 [英] Custom prototype chain for a function
问题描述
我很好奇我是否可以将一个对象包含到函数原型链中。我的意思是:
I am just curious whether I can include an object into function prototype chain. What I mean:
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
。它是 Function 的实例,并继承自
Function.prototype
,因此您可以调用 test例如。.bind
。
You have a function test
. It is a instanceof Function
, and inherits from Function.prototype
so that you can call test.bind
for example.
然后,将函数的 prototype属性设置为从 Function继承的对象.prototype
。这意味着 test
的所有实例都将从该对象(以及Function.prototype)继承:
Then you set the "prototype" property of your function to an object inheriting from Function.prototype
. That means that all instances of test
will inherit from that object (and from Function.prototype):
var t = new test;
t instanceof test; // => true
t instanceof Function; // => true
然后,您覆盖自定义原型对象上的test属性。您这样做确实很不错,因为Function方法只能在函数(即可调用对象)上调用:
Then you overwrite the test property on your custom prototype object. You do good to do so, because Function methods should only be called on functions (i.e. callable objects):
>>> Function.prototype.bind.call({})
Unhandled Error: Function.prototype.bind: this object not callable
在使用 console.log
进行的测试中,您仅将函数方法应用于 test
函数,而不是实例。好,因为它们会失败。因此,我看不出为什么任何对象都应从 Function
继承-您不能构造不直接从 Function继承的函数
。
In your tests with console.log
you only apply the Function methods on your test
function, not on instances of it. Good, because they'd fail. So, I can see no reason why any objects should inherit from Function
- you can't construct functions that don't inherit directly from Function
.
这篇关于功能的定制原型链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!