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.
First and foremost, you should probably be considering some other way of doing this, because it is unlikely to be portable. I’m just going to assume Rhino for my answer.
Second, I’m not aware of any way in Javascript of assigning a function’s body after construction. The body is always specified as the object is constructed:
Now, there’s a non-standard Mozilla extension in the form of a
__proto__property on every object. This allows you the change the inheritance chain of any object. You can apply this to your function object to give it a different prototype after construction: