I would like to create a Javascript class that I can use like so:
var f = new myFunction(arg1, arg2);
f.arg1; // -> whatever was passed as arg1 in the constructor
f();
f instanceof myFunction // -> true
typeof f // -> function
I can treat it like a normal object, even adding the native Function
object to the prototype chain, but I can't call it like a function:
function myFunction(arg1, arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
}
myFunction.prototype = Function
var f = new myFunction(arg1, arg2); // ok
f.arg1; // ok
f(); // TypeError: f is not a function, it is object.
f instanceof myFunction // -> true
typeof f // -> object
I can have the constructor return a function, but then it's not an instance of myFunction
:
function myFunction(arg1, arg2) {
var anonFunction = function() {
};
anonFunction.arg1 = arg1;
anonFunction.arg2 = arg2;
return anonFunction;
}
var f = new myFunction(arg1, arg2); // ok
f.arg1; // ok
f(); // ok
f instanceof myFunction // -> false
typeof f // -> function
Any suggestions? I should add that I really want to avoid using new Function()
since I hate string code blocks.