JavaScript/Notes/Function/Template:Functions Double as Constructor

From Noisebridge Wiki
Jump to navigation Jump to search

Functions' prototype Property[edit]

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.

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());

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.

alert( String(c) );

However, when string concatenation is performed, the hint for the primitive value is not string. Instead, the Object's valueOf may be called.

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"