Javascript "polymorphic callable objects"

I saw this article about polymorphic called objects and tried to make it work, however it seems that they are not polymorphic or, at least, they don’t follow 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); 
+7
javascript
Jul 03 2018-11-17T00:
source share
1 answer

You will need to change this:

 var X = callableType(function() { this.callOverload = function(){console.log('called!')}; }); 

:

 var X = new (callableType(function() { this.callOverload = function(){console.log('called!')}; })); 

Notice the new as well as the parentheses around the callableType call.

The brackets allow you to call callableType and return a function that is used as the constructor for new .




EDIT:

 var X = callableType(function() { this.callOverload = function() { console.log('called!') }; }); var someType = X(); // the returned constructor is referenced var anotherType = X(); // the returned constructor is referenced someType.prototype.hello = "hello there"; // modify the prototype of anotherType.prototype.hello = "howdy"; // both constructors var some_i = new someType(); // create a new "someType" object console.log(some_i.hello, some_i); var another_i = new anotherType(); // create a new "anotherType" object console.log(another_i.hello, another_i); someType(); // or just invoke the callOverload anotherType(); 

I really don't know how / where / why you are using this template, but I believe there is a good reason.

+6
Jul 03 2018-11-17T00:
source share



All Articles