2010-06-18 37 views
5

我正在學習JavaScript,我不明白爲什麼你要製作不是「特權」的方法,也就是說,沒有在構造函數中定義,而是在類的原型中定義。我明白封裝和所有的想法,但是你絕不會在其他大部分的OO世界中封裝一個類的部分。爲什麼使用非特權方法?

回答

18

當在構造函數中定義函數時,每次調用構造函數時都會創建該函數的新實例。它也可以訪問私有變量。

var myClass = function() { 
    // private variable 
    var mySecret = Math.random(); 

    // public member 
    this.name = "Fred"; 

    // privileged function (created each time) 
    this.sayHello = function() { 
     return 'Hello my name is ' + this.name; 
     // function also has access to mySecret variable 
    }; 
} 

當在原型上定義函數時,該函數僅創建一次,並且該函數的單個實例被共享。

var myClass = function() { 
    // private variable 
    var mySecret = Math.random(); 

    // public member 
    this.name = "Fred"; 
} 

// public function (created once) 
myClass.prototype.sayHello = function() { 
    return 'Hello my name is ' + this.name; 
    // function has NO access to mySecret variable 
}; 

因此,在原型上定義一個函數會產生較少的對象,可以提供更好的性能。另一方面,公共方法不能訪問私有變量。更多的例子和推理可以在這裏找到:http://www.crockford.com/javascript/private.html

+0

@aharon:以防萬一:謹慎使用['this''](http://blog.niftysnippets.org/2008/04/you-must-remember -this.html)。 – 2010-06-18 01:48:05

+0

我更新了我的答案,使公共,私人和特權之間的區別更加清晰。 – Greg 2010-06-18 01:56:54

相關問題