var foo = {
x: 1,
y: (function () {
return ++this.x;
})()
};
console.log(foo.y); // undefined rather than 2
Let’s say that I want to be able to reference foo.y without using foo.y(). Is that possible?
The above obviously doesn’t work, and I’m assuming it is because closure references a different this.
If you want to access y as a property and not a function, and have it return the current value of foo.x, the only way I can think of is using getters/setters, which is part of the ES5 spec, and adopted in most of the modern browsers (but not really useable if you’re supporting older browsers).