JavaScript/Notes/Function/Template:Functions Double as Constructor: Difference between revisions

From Noisebridge
Jump to navigation Jump to search
No edit summary
Fnord (talk | contribs)
m Undo revision 45943 by IgAZwmawpK (talk)
 
Line 1: Line 1:
== Functions' prototype Property ==  
== Functions' prototype Property ==  
Every user-defined func[[File:Past1.jpg]]
Every user-defined function gets a prototype property for free. This property is assigned to the instance's <nowiki>[[Prototype]]</nowiki> and is used for prototype inheritance, or "shared properties" of each instance.
[[File:Past2.jpg]]
[[File:Present1.jpg]]
tion gets a prototype property for free. This property is assigned to the instance's <nowiki>[[Prototype]]</nowiki> and is used for prototype inheritance, or "shared properties" of each instance.
<source lang="javascript">
<source lang="javascript">
function Colorized(name, favoriteColor) {
function Colorized(name, favoriteColor) {

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>