0

I guess this have been both asked and answered before, but I don't really know what to search for.

Anyway, lets say we've got the following JavaScript:

var foo = {
   myVar : 'Hello',
   bar : function() {
      //Fetch the myVar variable
   }
}

How do I access the variable where mentioned?

Thank you in advance!

1 Answer 1

2
var foo = {
   myVar : 'Hello',
   bar : function() {
      alert(this.myVar);
   }
}

Try it

Sign up to request clarification or add additional context in comments.

3 Comments

Seems to work the way you write it! How would the alert line look like if the foo object is in another object?
I saved your JS. You had a = instead of :. It works now. You should read documentation about object literals in JS if you want to understand what happens behind the scene :)
Ops, as simple as that, didn't notice it. Thank you. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.