Alex Mills Alex Mills - 1 year ago 92
Node.js Question

Object.create(Function.prototype) => create Function which inherits properties

I am looking for a way to construct a function that has some inheritance.

What I am looking for is an object that is a function that can be instantiated in a program, but that has new properties attached to it's prototype.

So, what we shouldn't do is this:

Function.prototype.x = function(){


Function.prototype.y = function(){


so what I want to do is something like:

const proto = Object.create(Function.prototype);

proto.x = function(){};

proto.y = function(){};

however, at some point later in the program, I would like to actually define the function body for proto, so that I can actually call proto like a function:


is there a way to do this? The above definitely does not work :)

This is a little closer, and the error message is telling:

function F(){


F.prototype = Function.prototype;

var f = new F();


Run the above and we get:

TypeError: Function.prototype.apply was called on [object Object],
which is a object and not a function
at Object. (/Users/amills/WebstormProjects/oresoftware/suman/exp7.js:15:3)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:449:3

Answer Source

The right way to do this is as follows!

step 1

create an Object which inherits from Function.prototype

const obj = Object.create(Function.prototype);  // inherits many properties, etc

step 2

later in your program declare the function

const f = function(){};

step 3

set the __proto__ of f to obj

Object.setPrototypeOf(f,obj); which is basically equivalent to f.__proto__ = obj;

....this seems to work without any problems, thanks for everyone's help!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download