Los getter/setters tienen que estar en el alcance que pueden ver las variables privadas y el único ámbito que puede ver estas variables son las partes internas del constructor. Es por eso que estas variables son en realidad privadas. Entonces, para hacer setters/getters para ellos, debes poner las funciones en ese alcance que pueda verlos. Esto funcionará:
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
Se puede ver que funcione aquí: http://jsfiddle.net/jfriend00/hYps2/.
Si desea un captador genérico/definidor de soldados, que podría hacerlo de esta manera:
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
Y, si quieres crear en torno a la naturaleza privada de estas variables que no tiene sentido para mí (mientras que también les podría hacer que las variables de instancia estándar después), puede hacerlo de esta manera:
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;
}
Ejemplo aquí: http://jsfiddle.net/jfriend00/EKHFh/.
Por supuesto, esto arruina la naturaleza privada de las variables, por lo que no tiene ningún sentido hacerlo de esta forma, ya que hacer que sean variables de instancia regulares sería más fácil y tendría el mismo control de acceso.
Y, para completar, este es el método de variable de instancia normal que le permite libremente agregar métodos de acceso al prototipo, pero las variables no son privadas.
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;
}
Por lo tanto, en Javascript, el concepto de "prototipo" es un dulce de azúcar para tratar de pretender que está orientado a objetos. –
Pero esta es una declaración estática de getters/setters, no dinámica.Necesito agregarlos dinámicamente a winClass. – Wilk
@Wilk: defina "dynamic getter/setter" y describa lo que está tratando de lograr. – jfriend00