Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference an object property in 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 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.

like image 626
oevna Avatar asked May 24 '26 04:05

oevna


1 Answers

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).

var foo = {
    x: 1,
    get y() {
        return this.x;
    }
};
like image 66
Brad Harris Avatar answered May 25 '26 18:05

Brad Harris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!