Skip to content Skip to sidebar Skip to footer

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 bo

Solution 1:

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

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 instanceofFunction; // => true

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({})
UnhandledError: Function.prototype.bind: thisobject not callable

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.

Post a Comment for "Custom Prototype Chain For A Function"