I came up with the situation below:
function Dog () {
"use strict";
this.age = 1;
var name = "Fido";
this.getName = function () { return name; }
}
And now I'm creating a new instance of the "Dog" class and printing the variable's values.
var d = new Dog;
document.write('<strong>Dog age:</strong> ' +d.age); \\Outputs "1" as expected
document.write('<br/>');
document.write('<strong>Dog name:</strong> ' +d.name); \\Outputs "undefined" as expected, 'cause it's a private variable.
document.write('<br/>');
document.write('<strong>Get Dog name:</strong> ' +d.getName()); \\Outputs "Fido", as expected.
But let's say I want to change the Dog's name, like this:
d.name = "Stinky";
document.write('<br/>');
document.write('<strong>Dog name Again:</strong> ' +d.name);
document.write('<br/>');
document.write('<strong>Get Dog name Again:</strong> ' +d.getName());
Based on this, I got a couple of questions:
- Why on earth "d.name" didn't showed me "undefined"? Isn't "name" a private variable? I suppose you can't change private variables values, am I right? I wonder if this process have created a new variable, but this time, a public one, and with the same name. If so, is there a way to prevent the creation of new variables every time I try to assign a new property with the same name? Is there a way to throw a "type error" or something (well, this was what I expected).
- And at last: Why "getName" printed the original value, "Fido", even after I assigned a new value to it ?
Any ideas?
Here's a fid to make things easier.