javascript - function prototype inheritance with new keyword -


i making sure understood javascript's new , prototype keywords correctly simple code put not behaving expect.

var classa = function() {     return {         shout: function() {              alert("i can shout");         }     }; }; classa.prototype.shoutlouder = function() {      alert("i can shout"); };  var instance = new classa(); instance.shout();  // why not available? instance.shoutlouder(); 

when instance variable attempts invoke shoutlouder it's failing "uncaught typeerror: instance.shoutlouder not function".

but, in mozilla docs, says when using new create object:

a new object created, inheriting foo.prototype.

where wrong in understanding?

here jsbin above code-snippit.

you're losing access function's (class') prototype object because you're returning new object out of function:

var classa = function() {     return {         shout: function() {              alert("i can shout");         }     }; }; 

whereas should doing:

var classa = function() {     this.shout = function() {         alert("i can shout");     }; }; 

this still give access prototype object (and delegation chain still work) because new keyword return 'this' class.


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -