- Adding a function as a property would lead to each
instance having a copy of all functions.
- Instead, there is a prototype for each
constructor which contains all the properties every instance
gets.
function Rectangle(w, h){
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() {
return this.width * this.height;
}
var r1 = new Rectangle(2,3);
r1.area()
- Thus, an object inherits properties from its
prototype object.
- Use
hasOwnProperty("area")
to determine if
"area" is not inherited.
- A prototype object can inherit from its own prototype
object, and so on.......
- The properties' values are not copied at creation
time. They are dynamically looked up at runtime.
- Look up happens only when reading the value of a
property. When writing, the object obtains its own copy of the
property, if inherited.