I'm learning the basics of OOP in JavaScript and I'm having some issues with this example:
var Human = function (first, surname) {
var x = {};
Object.defineProperties(x, {
first: {
get: function () {
return this.first;
},
set: function (value) {
this.first = value;
}
},
surname: {
get: function () {
return this.surname;
},
set: function (value) {
this.surname = value;
}
}
});
return x;
};
var alex = new Human("Alex", "Corlette");
This: console.log(alex);
Outputs:
{ }
And this: console.log(alex.first);
Outputs:
Uncaught RangeError: Maximum call stack size exceeded
Anyone got any idea what I'm doing wrong?
The problem is the scope. Since you are defining a property and in the getter and setter referencing to those same getters and setters.
The example could be fixed by removing the this keyword.
var Human = function (first, surname) {
var x = {};
Object.defineProperties(x, {
first: {
get: function () {
return first;
},
set: function (value) {
first = value;
}
},
surname: {
get: function () {
return surname;
},
set: function (value) {
surname = value;
}
}
});
return x;
};
var alex = new Human("Alex", "Corlette");