Jack Clark Jack Clark - 1 year ago 53
Javascript Question

How are javascript libraries available when wrapped in an IIFE? Isn't the execution context disposed?

In the Underscore js library all the code is wrapped inside:

(function() {
//rest of library etc.

I understand wrapping the function() in () is for namespace purposes, and that the .call(this) invokes the library on startup passing the window object.

But my understanding is that once an execution context has finished running it is 'deleted'. So how is all of the code inside this library available to other script files?

Answer Source

This concept can be explained here with a simple example:

//library code starts

    this.hello = function(){

//library code ends

//outside the library
//will print the function showing that it is available outside the library
console.log(window.hello); //will print the function

//will console.log hello

Since call function calls the IIFE with this (which points to window object), even if you want to get the value of window object outside the library code you can get that easily.

Since hello function is binded to window object it is available to be called outside the library code.

This applies to any function or variable bound to the window object.

Understanding the execution context

The execution context is only made when a particular function is called or some variable/ object is being used.

For each called function, a different execution context is made which is disposed off when the execution finishes. That does not mean the object (window) in this case will not be a part of the memory any more.

You may call a function 10 times with different arguments and it will create 10 different execution contexts assigning memory at runtime and destroying it once the execution is completed. It has nothing to do with the library code being loaded.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download