Question

what's the difference between them ?
①function's scope-->②[[scope]]---->③scope

var scope = 'window';
var someFunction = function(){
    something go here....
}

someFunction's scope
someFunction[[scope]]
window scope
is that right?

Was it helpful?

Solution

If you want to understand the scope chain, you should read Richard Cornford's article on JavaScript Closures, particularly the part on Identifier Resolution, Execution Contexts and scope chains.

Briefly, the scope chain travels from variable/activation object to variable/activation object, stopping with the global object (since the global object is effectively the activation/variable object for the global execution context).

So in the case of:

var fred;

function foo() {
    alert(fred);
}

The identifier fred is made a property of the global variable/activation object (which in the case of global code is the global objet itself). When foo() is called, a new variable/activation object is created with a scope chain that includes the global object. The identifier fred is first resolved on the internal variable object, and since it won't be found there, the next object on the chain (the global object) is searched.

Similarly for:

function foo() {
    function bar() {
        alert(fred);
    }
    bar();
}

So when foo() is called, it then calls bar(), and now fred is resolved against firstly bar's variable object, then foo's, then the global object.

Once you understand execution context, you will also realise why calling the value of this "context" is misleading.

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