Skip to content Skip to sidebar Skip to footer

Custom Function Class

I'm working on a project that involves constructing functions from other functions. I had the idea of writing a class to simplify things but I haven't been able to get it to work w

Solution 1:

Fascinating idea. I don't believe you can do it with standard ECMAScript yet, not even using ES5.

ES5 gives us better access to and control over the prototype, including providing a means of setting the prototype when creating objects (without having to go through constructor functions) with Object.create, but you can't construct functions via that mechanism. And that's what you would have to do, because instanceof uses the abstract spec [[HasInstance]] method, which is currently only implemented by functions, and the function implementation of it works by seeing if the object's underyling prototype ([[Proto]]) is === to the function's prototype property. The only standard way to set the object's underlying prototype is to create it via new MyFunction or via Object.create, and neither mechanism creates a function object.

ES.next may make this possible. There's a proposal that's been promoted to "harmony" status (so, fairly advanced) for a "set prototype operator", <|, which is intended to solve many of the problems currently solved via __proto__. One of the things it's for is "Setting the prototype of a function to something other than Function.prototype". Using it (in its current form), your MyFunction would look something like this:

functionMyFunction () {
  returnMyFunction.prototype <| function () { return'hello'; };
}
MyFunction.prototype = Object.create(Function.prototype);

That last bit is to make it that MyFunction.prototype is an object with the prototype Function.prototype, so that functions constructed via MyFunction have call, apply, bind, etc.

Post a Comment for "Custom Function Class"