gen_Eric
gen_Eric

Reputation: 227200

Variable scope inside constructor

In JavaScript, functions can always access global variables. I have a class that I am using, and it references global variables. Here's a similar class:

function Test(){
    this.abc = abc;
}

If I set the global abc then call this, it works.

var abc = 123,
    testA = new Test;

console.log(testA.abc); // 123

But what if I don't want abc to be global? I wrapped the code in a function call, but I get an error saying abc is not defined.

(function(){
    var abc = 123,
        testA = new Test;  // ERROR: abc is not defined

    console.log(testA.abc);
})();

How can I read local variables inside a JavaScript constructor without adding variables to the global scope?

Upvotes: 0

Views: 382

Answers (1)

Alnitak
Alnitak

Reputation: 339786

The problem is that local variables have lexical scope.

That means that to be resolved they must be within the same code block, or in enclosing code blocks.

Your code would only work if the definition of Test was also within the IIFE:

(function(){
    var abc = 123,
        testA = new Test;  // ERROR: abc is undefined

    function Test() {      // this will be hoisted
        this.abc = abc;
    }

    console.log(testA.abc);
})();

Upvotes: 3

Related Questions