0

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?

2
  • Why not pass abc as a parameter to Test(.)? Commented May 30, 2013 at 14:23
  • @mbratch: Because I didn't write Test. I was just wondering if I could "fix" it without re-writing. :) Commented May 30, 2013 at 14:24

1 Answer 1

3

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);
})();
Sign up to request clarification or add additional context in comments.

8 Comments

Yeah, I was afraid there was no way around this.
so you're trying to make Test work without rewriting it, but referring to a local variable instead of global?
Yeah, pretty much. Test was written by someone else, and relies on global variables (for whatever reason). I hate global variables and was wondering if I avoid them.
You might be able to make it work using with, but that'll probably cause more problems than it fixes. It's also not allowed in ES5 "strict" mode.
I thought of with, but I am using 'use strict'; on my code :)
|

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.