nazir don
nazir don

Reputation: 1

how can global function expression can access variable inside containing function in javascript

Here is an example:

function outerFunc(){
    //some variable 

    var x = 10;

    Obj = function(){  //Its global function created without var keyword
        this.a = x;
    }
}

So now when I create new instance of Obj object after calling the outerFunc function.

outerFunc();

myObj = new Obj();

myObj.a;  //prints 10 

So I wonder how can it read containing functions private variable x when I define Obj as global constructor, it still can read the value.

Upvotes: 0

Views: 88

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382434

You can't access the property x declared in the closure from outside.

Here, you don't read the value of the private variable x, but the copy you made and stored into a.

If your question is why you could access x from inside the function Obj : that's simply how closures work : a function can access the variables of the scope in which it was declared. The fact that this function is assigned to the Obj variable and that this variable is global changes absolutely nothing.

Here's some additional reading : the MDN on closures

Upvotes: 2

Related Questions