Wednesday, September 30, 2015

put a method on a function in JavaScript?

Instead of bolting all of the properties from an object onto another object as suggested in the seventh bullet here, prototype may be similarly used to attach just one new property to a function like so:

function Foo(name) {
   this.name = name;
}
 
Foo.prototype.myName = function() {
   return this.name;
}
 
var a = new Foo("a");
var b = new Foo("b");
 
alert(a.myName());
alert(b.myName());

 
 

This example is pretty much just stolen from page 97 of Kyle Simpson's book "this & OBJECT PROTOTYPES as the only thing I've added myself is the alerts wrapping the two last lines. The second to last line will give us "a" in an alert and the last line will afterwards give us "b" in an alert. However, if I were to remove the word prototype from the code above (and, yes, also one of the periods either leading it or following it) the code would not work at all. It would break. You have you use prototype as a keyword to append a property to a function which is kinda ghetto to begin with, eh? This allows a method on a function (is it a "method" if it's not on an object?) to be found via delegation when using a "constructor" which Mr. Simpson's book will make quite clear to you is not really a constructor but instead just a convenience thing that feels like a constructor in another language.

No comments:

Post a Comment