The exact same question is asked here define property in constructor, but i don't feel that the answers are satisfactory. The code is copied from the book "The Principles of Object Oriented JavaScript", with a slight modification to make the question more clear.
function Person(xname) {
Object.defineProperty(this, "name", {
get: function() {
return xname;
},
set: function(newName) {
name = newName;
},
configurable: true,
enumerable: true
});
this.sayName = function() {
console.log(this.name);
};
}
var One = new Person("Mark");
One.sayName();
console.log(One.name);
//output:
//Mark
//Mark
I have modified parameter name to xname, because it was even more confusing the use of local variable and object property with the same name.
I doubt that this code is working as intended but it confuses me even the way that it is doing something.
I understand that it is using Object.defineProperty inside the constructor to create a property on the newly created instance called "name".
The getter method returns xname and yet xname goes out scope after the line: var One = new Person("Mark"); How can later in the code object's One getter manage to return the value of xname??
And it is the value of xname, because if i change the getter method to return name, like it should work, the engine reports an error name is not defined. (get: function() {return name;})
Not to mention that the setter method doesn't work at all. If i code One.name = "Mickey", One.name is still set to "Mark".
There is no assignment of xname to .name or there is but I don't see it?!