我喜欢闭包,因为你可以从它们制作一个API,但它很糟糕,你不能拥有多个实例。闭包和多个实例
var Person = (function() {
// private properties and methods
var Constr, name;
// public API
Constr = function (n) {
name = n;
};
Constr.prototype.sayName = function(){return name;};
return Constr;
}());
var person1 = new Person('Foo');
var person2 = new Person('Bar'); //New values will overwrite the name because of the closure.
console.log(person1.sayName()); //Bar
console.log(person2.sayName()); //Bar
是否有其他办法可以使用原型来访问私有成员和创建不同的实例?
他们是私人,但不是唯一的每个实例。不要担心JS中的封装,可以使用'this._name',所以下划线是一个意思是“私有”的约定。 – elclanrs
原型方法是共享的,所以它们不能以每个对象为基础访问变量。 @elclanrs:在大多数情况下,解决方案应该绰绰有余。否则,你将放弃原型方法,并为每个实例分配自己的方法。 –
@ cookiemonster - 但公共方法可以通过特权方法访问私有成员,所以它不是世界的尽头,只是更低效。 :-) – RobG