mardi 14 juin 2016

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

This question already has an answer here:

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype

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:

proto();

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();

f.apply(null);

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

Aucun commentaire:

Enregistrer un commentaire