getter/setter 方法必须在能看到私有变量的作用域内,而唯一能够看到这些变量的作用域是构造函数的内部。 这就是为什么这些变量实际上是私有的原因。 因此,要为它们创建 getter/setter,必须将函数放在可以看到它们的作用域中。以下代码可行:
function winClass (posX, posY, w, h) {
var x = posX || 0;
var y = posY || 0;
var width = w || 0;
var height = h || 0;
this.getX = function() {return(x);}
this.setX = function(newX) {x = newX;}
}
var win1 = new winClass (10, 10, 100, 100);
alert(win1.getX());
你可以在这里看到它的运作效果:http://jsfiddle.net/jfriend00/hYps2/。
如果你想要一个通用的私有变量 getter/setter,你可以像这样做:
function winClass (posX, posY, w, h) {
var privates = {};
privates.x = posX || 0;
privates.y = posY || 0;
privates.width = w || 0;
privates.height = h || 0;
this.get = function(item) {return(privates[item]);}
this.set = function(item, val) {privates[item] = val;}
}
var win2 = new winClass(10,10,100,100);
alert(win2.get("x"));
如果你想绕过这些私有变量的限制,虽然这对我来说毫无意义(因为你可以把它们作为标准实例变量处理),你可以像这样操作:
function winClass (posX, posY, w, h) {
var privates = {};
privates.x = posX || 0;
privates.y = posY || 0;
privates.width = w || 0;
privates.height = h || 0;
this.getPrivates = function() {return(privates);}
}
winClass.prototype.getX = function() {
return(this.getPrivates().x);
}
winClass.prototype.setX = function(newX) {
this.getPrivates().x = newX;
}
这里有一个例子:http://jsfiddle.net/jfriend00/EKHFh/。
当然,这会破坏变量的私有性质,所以用这种方法没有任何意义,因为将它们设置为常规实例变量会更容易,且具有相同的访问控制。
还有一种正常的实例变量方法,可以自由地向原型添加访问器方法,但是变量不是私有的。
function winClass (posX, posY, w, h) {
this.x = posX || 0;
this.y = posY || 0;
this.width = w || 0;
this.height = h || 0;
}
winClass.prototype.getX = function() {
return(this.x);
}
winClass.prototype.setX = function(newX) {
this.x = newX;
}