0

So if I have some javascript like:

Foo.init = function(options) {
  Bar.set_listener('some_event', function() {
    console.log(options);
  });
};

where I call Foo.init with some options like Foo.init({whatever: 'hi'}) and that Bar.set_listener method takes the callback and stores it, and then invokes it at some later time when 'some_event' is triggered....

will console.log print undefined or {whatever: 'hi'} ? The answer seems to be {whatever: 'hi'} but that confuses me. How does this callback when invoked have any idea how to reference the options variable passed in to Foo.init?

3
  • You need to read up on 'closures' in Javascript. The explanation is too long to be an answer here. Commented Mar 5, 2013 at 23:14
  • en.wikipedia.org/wiki/Closure_%28computer_science%29 Commented Mar 5, 2013 at 23:15
  • It does log {whatever: 'hi'}. How, that's an implementation detail. Commented Mar 5, 2013 at 23:16

1 Answer 1

2

The ability of an inner function to reference state defined in an outer function is known as closures. This is a feature present in the majority of languages that allow for lambdas, or function values.

How it's implemented is worthy of a post much longer than can really be said in a Stack Overflow answer. But in summary the Javascript runtime will persist the values defined in an outer function so long as there is an inner function alive that references them.

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

Comments

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.