I saw this article on polymorphic callable objects and was trying to get it to work, however it seems that they are not really polymorphic, or at least they do not respect the prototype chain.
This code prints undefined, not "hello there".
Does this method not work with prototypes, or am I doing something wrong?
var callableType = function (constructor) {
return function () {
var callableInstance = function () {
return callableInstance.callOverload.apply(callableInstance, arguments);
};
constructor.apply(callableInstance, arguments);
return callableInstance;
};
};
var X = callableType(function() {
this.callOverload = function(){console.log('called!')};
});
X.prototype.hello = "hello there";
var x_i = new X();
console.log(x_i.hello);
You’d need to change this:
to this:
Notice the
newas well as the parentheses around thecallableTypeinvocation.The parentheses allows
callableTypeto be invoked and return the function, which is used as the constructor fornew.EDIT:
I really don’t know how/where/why you’d use this pattern, but I suppose there’s some good reason.