Reputation: 1604
How come this getter syntax works without Object.defineProperty
?
var Vector = function(x, y) {
this.x = x;
this.y = y;
}
Vector.prototype = {
getX: function() {
return this.x;
}
}
var vector = new Vector(22, 1);
vector.x = 3;
alert(vector.getX());
And this getter syntax doesn't work (in JSFiddle and CodePen)?
var Vector = function(x, y) {
this.x = x;
this.y = y;
}
Vector.prototype = {
get x() {
return x;
}
}
alert(new Vector(3, 4).x);
What is the difference between these getter syntaxes and when should I use them?
Upvotes: 1
Views: 53
Reputation: 255025
You have 2 issues with the latter example:
You are referring to the not existing variable x
: JS does not work like C++ or C# or Java where you just specify a member name, but you must use this
reference to address it. So it must be this.x
When you fix the #1 the second problem appears: a stack overflow.
Vector.prototype = {
get x() {
return this.x;
}
}
This code defines a getter that accesses itself to return a value. That causes the getter to be invoked so that it could invoke itself once again, infinitely.
The solution for it would be to use different names for the data member itself and its getter (like this.x
vs this.x_
)
PS: To be completely precise "And this getter syntax doesn't work" --- it's not a syntax problem, since the code is syntactically correct. The problem appears in runtime and is a problem of the code logic.
Upvotes: 3