用JavaScript代表原型

时间:2016-11-03 19:37:06

标签: javascript

方法委派(delegate prototype)如何保留内存资源?

由于方法委托保留了内存,这是方法委托/原型继承优于经典继承的原因之一吗?

2 个答案:

答案 0 :(得分:1)

通过原型委派方法可以节省内存,因为这意味着您不需要同一功能的多个副本。

function A() {
  this.hello = function() {
    console.log('A new function is created in memory every time');
    console.log('an instance of A is created');
  };
}

function B() { }
B.prototype.hello = function() {
  console.log('Only one function is created and every instance');
  console.log('of B shares this one function');
};

至于为什么通过原型使用方法委派比使用JavaScript 中的经典继承更好,这是因为JavaScript实际上不支持经典继承。你看到的任何模仿经典继承的东西都是:模仿。

答案 1 :(得分:1)

原型继承并不比经典继承更受欢迎,只是JavaScript不是编译语言,因此需要采用不同的方法。

通过将方法(行为)附加到原型,它们将为使用该原型的所有实例存储一次。如果您要将它们附加到实例本身,每个实例将占用更多内存,只是为了存储与任何其他实例没有区别的行为。

这就是为什么通常将存储基元(字符串,数字,布尔值)的属性创建为实例属性,因为它们的值可能因实例而异(即p1.name =“Scott “,p2.name =”玛丽“)。但是存储函数的属性模拟方法(行为),并且返回值(比如名称)的行为不会从实例更改为实例。所以方法往往被添加到原型中。

例如:

    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
    console.log(p1.hasOwnProperty("getName"));  // false
    console.log(p2.hasOwnProperty("getName"));  // false
    
    // 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