How does JavaScript access elements from a iframe that is no longer in the DOM when using a callback function?

StackOverflow https://stackoverflow.com/questions/22547963

  •  18-06-2023
  •  | 
  •  

Question

I don't know the best way to explain this in words so here is an example of my question: http://jsfiddle.net/efZyt/

(iframe source is here: http://jsfiddle.net/H6rLQ/ )

  1. Click the 'Change Source' button.
  2. Type something into the input.
  3. Repeat this a few times.
  4. Click on the Repeat Text button.

You will get an alert that will read back to you the text that you typed into the box each step of the way.

I'm a bit confused how the callback function

function(){ alert($('#getSomeText').val()); }

gets loaded into the callback array prior to the text value existing, the function gets called after the value no longer exists (or rather, exists somewhere I can't find) and yet it is able to produce all the values.

I can't figure out where the values are being held for the callback to access them. Does the whole instance of the iframe get preserved as a closure context somewhere for the callback to run in or something?

Was it helpful?

Solution

The is the beauty of JavaScript. The value is not being store anywhere as you would think! This is the magic of 'closures'.

Closure is basically the concept of a variable being alive even after it's scope has ended.

For example:

function outerFunction() {
 innerVar = function innerFunction() {
  alert('hello');
 }
 return innerVar;
}
var outterVar = outerFunction();
outterVar();

The above will output 'hello'. Note, the outerFunction has finished executing and the scope of 'innerVar' is also over; however, interestingly we can still execute a function defined in the outer function.

Similarly, when you pass a function to parent.register, you are NOT passing the actual value obtained by 'val()'; you are passing a function which will later be executed and internally will act as a a closure.

When it does get executed, it then takes the value by using 'val()' of the element present inside that 'closure' function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top