javascript "polymorphic callable objects" -


i saw this article on polymorphic callable objects , trying work, seems not polymorphic, or @ least not respect prototype chain.

this code prints undefined, not "hello there".

does method not work prototypes, or doing 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 change this:

var x = callabletype(function() {     this.calloverload = function(){console.log('called!')}; }); 

to this:

var x = new (callabletype(function() {     this.calloverload = function(){console.log('called!')}; })); 

notice new parentheses around callabletype invocation.

the parentheses allows callabletype invoked , return function, used constructor new.


edit:

var x = callabletype(function() {     this.calloverload = function() {         console.log('called!')     }; });  var sometype = x();      // returned constructor referenced var anothertype = x();   // returned constructor referenced  sometype.prototype.hello = "hello there";  // modify prototype of anothertype.prototype.hello = "howdy";     //    both constructors  var some_i = new sometype();           // create new "sometype" object console.log(some_i.hello, some_i);  var another_i = new anothertype();     // create new "anothertype" object console.log(another_i.hello, another_i);  sometype();      // or invoke calloverload anothertype(); 

i don't know how/where/why you'd use pattern, suppose there's reason.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -