2012-01-15 54 views
4

Snippet1定義的方法的區別在於:使用以下兩種

var box = function() {}; 

box.prototype.open = function { 
}; 

Snippet2:

var box = function() { 
     this.open = function() { 
     }; 
    } 

這兩個之間的任何差異,哪一個更好?

回答

5

我們假設box是一個構造函數,所以你在做new box()

如果是這樣......

  • 第一個版本將分享來自box構造函數創建的所有對象之間的open功能。

  • 第二個將爲從box構造函數創建的每個對象生成一個新的函數對象。

因此,第一個將比第二個更有記憶效率。


第一個版本:

new box     box prototype   object prototype 
+--------------+   +--------------+   +--------------+ 
|    |   |    |   |    | 
|    |--------->| open func |--------->|    | 
|    |  /|    |   |    | 
+______________+ / +______________+   +______________+ 
        /
        /
    new box  /
+--------------+/
|    |/
|    |/ 
|    | 
+______________+ 

第二個版本:

new box    box prototype   object prototype 
+--------------+   +--------------+   +--------------+ 
|    |   |    |   |    | 
| open func |--------->|    |--------->|    | 
|    |  /|    |   |    | 
+______________+ / +______________+   +______________+ 
        /
        /
    new box  /
+--------------+/
|    |/
| open func |/ 
|    | 
+______________+ 
+0

但是(因爲你沒有明確地說)第二個更合適_if_出於某種原因需要爲每個實例分別定義函數 - 這不是一個很常見的情況,但仍然是.. – nnnnnn 2012-01-15 07:21:46

+0

@nnnnnn:是的,好點。在構造函數中創建函數並直接分配的確有一些有效的場合。 – 2012-01-15 07:24:11

5

@am不是我什麼是正確的。第一種方法是有效的方法。 如果您需要私有變量,第二種方法很有用。

var box = function() { 
    var _message = "hello world"; 
    this.func2 = function(){ 
     console.log(_message); // prints hello world 
    } 
}; 

box.prototype.func1 = function() { 
    this.func2();    // prints hello world 
    console.log(_message);  // throws ReferenceError: _message is not defined 
}; 
+1

+1用於提供爲每個對象分配唯一功能的有效用例。 – 2012-01-15 07:25:22