Update: 2012.06.26 - See my conclusion bellow my original question.
I'm trying to figure out why this simple code doesn't initialize correctly. Yes, I'm from the Java world and I'm also a 'purist' and would like to do JavaScript properly.
Many (if not all) will recommend to declare the variables prefixed with a 'this' keyword and thus exposing all those variables without using proper setter and getter functions. To me this is unacceptable and does not reflect good OOP practice. They say JavaScript is an OOP language so why do people always try to bypass this I'll never understand!? But that's not the questions, so lets move on...
The problem with the following code is that when I run it in Chrome, it keeps telling me:
Uncaught ReferenceError: x is not defined
I could create a constructor which accepts the default values, but I'd rather not expose what the default value is suppose to be on those constructing the object (that is not good practice either). Also, during run-time, the setter methods would get invoked to change the 'x' and 'y' values for a specific instance. There are many 'Model' instances available at once!
So here is the simple code:
function Model() {
var x = 3;
var y = 'hello';
}
Model.prototype.getX = function() {
return x;
}
Model.prototype.getY = function() {
return y;
}
Model.prototype.setX = function(myX) {
x = myX;
}
Model.prototype.setY = function(myY) {
y = myY;
}
var model = new Model();
console.log("Model Y = '" + model.getY() + "'");
console.log("Model X = " + model.getX());
console.log("Model Y = '" + model.getY() + "'");
Thanks for your help...
Conclusion to the question (updated on 2012.06.26):
It is quite easy to conclude that what was requested (which happens to be something so simple) can not be done with JavaScript!
To my utmost surprise thought, as can be seen from the answers bellow, some will argue that since JavaScript does not support it, then you shouldn't need it or use it. Wow, that's really amazing!
I have argued for many years that JavaScript was not an OOP language and this simple question (and it's answers) goes to prove it.
So in the end it discusses me to admit defeat and you and I will both need to change our code to using the 'this' keyword for all class members. Once again, the language controls the programmer rather than the programmer controlling the language! And they wonder why over 2/3 of software projects fail every year!?