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