Skip to main content
AI Assist is now on Stack Overflow. Start a chat to get instant answers from across the network. Sign up to save and share your chats.
added 20 characters in body
Source Link
oevna
  • 1.3k
  • 2
  • 11
  • 10
var foo = { x: 1, y: (function () { return this++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()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 changesreferences a different this.

var foo = { x: 1, y: (function () { return this.x; })() }; console.log(foo.y); // undefined 

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 changes this.

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.

Source Link
oevna
  • 1.3k
  • 2
  • 11
  • 10

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 

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 changes this.