Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The getter/setters have to be in the scope that can see the private variables and the only scope that can see these variables is the internals of the constructor. That's why these variables are actually private. So, to make setters/getters for them, you have to put the functions in that scope that can see them. This will work:</p> <pre><code>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 </code></pre> <p>You can see it work here: <a href="http://jsfiddle.net/jfriend00/hYps2/">http://jsfiddle.net/jfriend00/hYps2/</a>.</p> <p>If you want a generic getter/setter for privates, you could do it like this:</p> <pre><code>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 </code></pre> <p>And, if you want to hack around the private nature of these variables which makes no sense to me (as you might as well make them standard instance variables then), you can do it like this:</p> <pre><code>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; } </code></pre> <p>Example here: <a href="http://jsfiddle.net/jfriend00/EKHFh/">http://jsfiddle.net/jfriend00/EKHFh/</a>.</p> <p>Of course, this ruins the private nature of the variables so there isn't really any point in doing it this way as making them regular instance variables would be easier and have the same access control.</p> <p>And, for completeness, here's the normal instance variable method that freely lets you add accessor methods to the prototype, but the variables aren't private.</p> <pre><code>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; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload