Is It Possible For An Object To Also Be A Function?
Solution 1:
Short answer, No. Yes! See proxy solution below.
In section 9.2.1 of the spec it outlines Function objects' internal [[Call]]
property that allows that object to be called as a function. There is currently no way I know of to modify that property, i.e. make an object into a function after its creation. It will be possible with a fully compliant implementation of ES 2015 to subclass Function and have callable objects (currently works in FF, for example). Even then, I didn't try anything more than making a paper-thin layer over the Function constructor itself. However, ES 2015 also includes Proxies, and one of the proxy traps is 'apply'.
class Person {
constructor(arg, body) {
this.fn = function(a) { this.a = a; };
return new Proxy(this, {
apply: function(target, thisArg, args) {
return target.fn.apply(target, args);
}
});
}
}
var person = new Person();
person(3);
person.a; //3
Tested in Chrome 49. Fails in FF unless Person extends Function and makes a call to super:
class Person extends Function {
constructor() {
super();
this.fn = function(a) { this.a = a; };
return new Proxy(this, {
apply: function(target, thisArg, args) {
return target.fn.apply(target, args);
}
});
}
}
var person = new Person();
person(3);
person.a;
According to MDN, the part about requiring the super
call is correct at least (for subclasses) but I am unsure whether Proxies should let you call a non-function the way chrome lets you.
UPDATE
I opened another question about which behavior is correct. For those too lazy to follow a hyperlink the calling of a non-function is a bug in some specific versions of chrome that has since been fixed.
Post a Comment for "Is It Possible For An Object To Also Be A Function?"