2009年2月15日 星期日

javascript memo: Classes, Constructors, and Prototypes

This solution works better but is still not optimal. Every rectangle created will have three properties. The width and height properties may be different for each rectangle, but the area of every single Rectangle object always refers to the same function (someone might change it, of course, but you usually intend the methods of an object to be constant). It is inefficient to use regular properties for methods that are intended to be shared by all objects of the same class (that is, all objects created with the same constructor).


Note that inheritance occurs automatically as part of the process of looking up a property value. Properties are not copied from the prototype object into new objects; they merely appear as if they were properties of those objects. This has two important implications. First, the use of prototype objects can dramatically decrease the amount of memory required by each object because the object can inherit many of its properties. The second implication is that an object inherits properties even if they are added to its prototype after the object is created. This means that it is possible (though not necessarily a good idea) to add new methods to existing classes.


Inherited properties behave just like regular properties of an object. They are enumerated by the for/in loop and can be tested with the in operator. You can distinguish them only with the Object.hasOwnProperty( ) method:

沒有留言: