2010-06-18 34 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

相关问题