Custom prototype chain for function

I'm just wondering if I can include an object in the 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 
+3
javascript prototype ecmascript-5
May 15 '12 at 9:03
source share
1 answer

You have a test function. This is instanceof Function and inherits from Function.prototype , so you can call test.bind , for example.

Then you set the "prototype" property of your function to an object that inherits from Function.prototype . This means that all test instances inherit from this object (and from Function.prototype):

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

Then you overwrite the test property on your own prototype object. You do this well, because function methods should only be called on functions (i.e. called objects):

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

In your tests using console.log you apply the Function methods only to your test function, not to its instances. Good, because they will fail. Thus, I see no reason why any objects should inherit from Function - you cannot create functions that are not inherited directly from Function .

+2
May 15 '12 at 11:21
source share



All Articles