How can I bind a property of an object to an anonymous function within the same object?
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 refer to foo.y without using foo.y () . Is it possible?
The above obviously doesn't work, and I'm guessing it's because the closure references are different from this.
source to share
If you want to access y as a property, not a function, and return the current value of foo.x to it, the only way I can think of is using getters / setters, which is part of the ES5 spec and is accepted in most modern browsers (but not very useful if you support older browsers).
var foo = {
x: 1,
get y() {
return this.x;
}
};
source to share
You are not declaring function y as a function, but as a result of a function call. It should be:
var foo = {
x: 1,
y: function () {
return this.x;
}
};
Or, if you just want to assign y to x:
var foo = {
x: 1,
y: this.x
};
UPDATE: It is NOT possible to make y synonymous with x. When you declare y it can be a value or a function. It cannot be a reference to another value.
source to share