getter/setters必须在可以看到私有变量的范围内,并且唯一可以看到这些变量的范围是构造函数的内部。这就是为什么这些变量实际上是私人的。所以,要为它们设置setter/getters,你必须把这些函数放在那个可以看到它们的范围中。这将工作:
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()); // alerts 10
你可以看到它在这里工作: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")); // alerts 10
而且,如果你想破解围绕这些变量的私有性质,这使得没有任何意义,我(你还不如让他们当时的标准实例变量),你可以做这样的:
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;
}
因此,在JavaScript中'原型'的概念是尝试假装它是面向对象的软件。 –
但是这是getters/setters的静态声明,而不是动态的。我需要动态地将它们添加到winClass。 – Wilk
@Wilk - 定义“动态getter/setter”并请描述你想要完成的事情。 – jfriend00