1

Is it posible to access the variable defined in parent function without creating the handler for it ?

So basically what i need is something like below.

var g=100;

(function f()
{ 

 var g=200;

 (function()
  {
    var g=300;

    console.log(g);            //300
    console.log(window.g);     //100
    console.log( ?? ) // how should i get value of g as 200 here ??

  })();

}();

Please note here that i dont want to create handler here. If i have only one function, and i want to access parent variable(same varible present in the current function) inside the function then i can use window.[variablename]

0

3 Answers 3

4

You must use different variable names, otherwise the variable from the parent scope will be masked by the one in the internal scope.

Overriding variable names between scopes is bad practice and should be avoided.

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

Comments

1

This is called Data Hiding. You can't access outer block data without help from a handler.

Comments

1

I know that there is a chosen answer already but I will put in my 2 cents in case it is useful for you.

Maybe something like this is what you want:

new (function () {
    this.msg = "hello 1";
    console.log(this.msg);

    new (function (parent) {
        this.msg = "hello 2";
        console.log(this.msg); // hello 2
        console.log(parent.msg); // hello 1
    })(this)
})()

You can keep creating inner scopes with the new keyword to achieve this tree-like structure of scopes where you can keep accessing the parent scope (which was also created using the new keyword.

1 Comment

Yes this will also work provided parent function is passed as an arguement. Thanks Shafeen.

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.