Yogesh Yogesh - 1 year ago 173
Javascript Question

Delegate prototype in JavaScript

How can Method delegation (delegate prototype) preserve memory resources?

Since method delegation preserve memory, is this one of the reason method delegation/prototype inheritance preferred over classical inheritance?

Answer Source

It isn't that prototypical inheritance is preferred over classical inheritance, it's simply that JavaScript is not a compiled language and so, it needs a different approach.

By attaching methods (behaviors) to the prototype, they are stored once for all instances that use that prototype. If you were to attach them to the instances themselves, each instance would take up more memory just to store a behavior that is no different than any other instance.

This is why, typically, properties that store primitives (strings, numbers, booleans) are created as instance properties, because their values can differ from instance to instance (i.e. p1.name = "Scott", p2.name = "Mary"). But properties that store functions simulate methods (behavior) and the behavior to return a value (say a name) doesn't change from instance to instance. So methods tend to be added to the prototype.

For example:

    function Person(name){
       // This is an "instance property". Every time an instance
       // of Person is created, that instance will store a name property
       // in the object's memory. This type of property needs to be set up
       // like this because each Person can/will have a different name.
       this.name = name; 
    // This method always does the same thing, regardless of
    // what instance it's dealing with, so it's better to store
    // it just one time on the object that all Person instances
    // will inherit from:
    Person.prototype.getName = function(){ return this.name; }

    // Both of these Person instances inherit from the same (one) Person
    // prototype. 
    var p1 = new Person("Scott");
    var p2 = new Person("Mary");
    // So while each instance reserves space to store a name:
    console.log(p1.name); // "Scott"
    console.log(p2.name); // "Mary"
    console.log(p1.hasOwnProperty("name"));  // true
    console.log(p2.hasOwnProperty("name"));  // true
    // Neither of those instances are storing the function for getName().
    // That is being stored just once in Person.prototype and p1 and p2
    // are inheriting that behavior:
    console.log(p1.getName()); // "Scott"
    console.log(p2.getName()); // "Mary"
    console.log(p1.hasOwnProperty("getName"));  // false
    console.log(p2.hasOwnProperty("getName"));  // false
    console.log(p1.__proto__.hasOwnProperty("getName"));  // true

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download