0

How can I access object foo? I want to pass it to the event listener. Do I have to make foo global?

function test(){
  var foo = {
    bar:2
  }
}
$('#bla').on('click',function(){
  foo.bar = 5;
});
4
  • 6
    You can't. foo is only available within the scope of test in the example code. Commented Sep 19, 2018 at 14:54
  • Does it mean I have to make any object I want to use in an event listener global or is there a more elegant way? Commented Sep 19, 2018 at 14:59
  • It doesn't need to be global, just within scope of all locations you want to use it. I'd suggest creating your own namespace and working within that. Commented Sep 19, 2018 at 15:01
  • @user3024814 You could wrap the function test and the event listener inside an IIFE and make the object foo outside of both but inside the IIFE. That way foo won't be global Commented Sep 19, 2018 at 15:02

1 Answer 1

1

Try Following

var foo={};
test();
function test(){
  foo.bar=2  ;
}
$('#bla').on('click',function(){
  foo.bar = 5;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="test" id="bla"/>

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

1 Comment

Wouldn't this make it a global variable / add it to window object?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.