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 without resorting to using __proto__.
Here's basically what my vision is.
function MyFunction () {
// ...
}
var myFn = new MyFunction();
myFn(); // executes without error
myFn instanceof MyFunction; // returns true
The following code does just that using __proto__
function MyFunction () {
var fn = function () { return 'hello'; };
fn.__proto__ = this;
return fn;
}
var myFn = new MyFunction();
alert( myFn() ); // hello
alert( myFn instanceof MyFunction ); // true
Here's something I've tried using valueOf
function MyFunction () {
this.fn = function () { return 'hello'; };
this.valueOf = function () { return this.fn; };
}
var myFn = new MyFunction();
alert( myFn instanceof MyFunction ); // true
alert( myFn.valueOf()() ); // hello
alert( myFn() ); // error
And here's something else extending the function to contain all the properties of MyFunction.
function MyFunction () {
this.foo = 'hello'
var fn = function () { return 'hello'; };
for ( var i in this ) {
fn[ i ] = this[ i ];
}
return fn;
}
var myFn = new MyFunction();
alert( myFn() ); // hello
alert( myFn.foo ); // hello
alert( myFn instanceof MyFunction ); // false
I don't want to use __proto__ because it's non-standard. Also, this was kind of a freak idea, I'd really like to get it to work, but if it's not possible I'll live. But I guess my question is, is what I'd like to do possible?