JavaScript/Notes/Function/Template:Functions Double as Constructor: Difference between revisions
Created page with "== Functions' prototype Property == Every user-defined function gets a prototype property for free. This property is assigned to the instance's <nowiki>Prototype</nowiki>..." |
m Undo revision 45943 by IgAZwmawpK (talk) |
| (One intermediate revision by one other user not shown) | |
(No difference)
| |
Latest revision as of 17:21, 31 December 2014
Functions' prototype Property
[edit | edit source]Every user-defined function gets a prototype property for free. This property is assigned to the instance's [[Prototype]] and is used for prototype inheritance, or "shared properties" of each instance. <source lang="javascript"> function Colorized(name, favoriteColor) {
this.name = name; this.favoriteColor = favoriteColor;
}
// alert(Colorized.prototype); // we get prototype for free. Colorized.prototype.toString = function() {
return this.name + ", " + this.favoriteColor;
};
var c = new Colorized("Mary", "red"); alert(c.toString()); </source>
The toString method is called by the engine when a primitive String value is required. For example, when calling the String constructor as a function, the engine finds the toString method and calls it.
<source lang="javascript"> alert( String(c) ); </source>
However, when string concatenation is performed, the hint for the primitive value is not string. Instead, the Object's valueOf may be called.
<source lang="javascript"> var o = {
name : "Greg",
toString : function() {
return "[object " +this.name + "]";
},
valueOf : function() {
return 10;
}
};
alert( o + " is valued at " + (+o)); // "10 is valued at 10" </source>