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