Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing variable in outer scope?

(function () {
    var x = 1;
    return {
        f: function (x) {
            alert(x);
        }
    };
}()).f(2);

Suppose I don't want to rename either variable. There is no way to, from within f, access the variable x, which was declared first - right?

like image 449
feklee Avatar asked Dec 30 '10 13:12

feklee


2 Answers

Correct. Because you have a different x in function (x), any attempt to access x will get that one (the nearest scope). It blocks access to any x in a wider scope.

like image 111
Quentin Avatar answered Nov 08 '22 11:11

Quentin


This allows you to use both x (1) and x (2) at the same time.

(function () {
    var x = 1;
    return {
        f: function (x) {
            alert(x); // paramter (=2)
            alert(this.x); // scoped variable (=1)
        },
        x:x
    };
}()).f(2);
like image 21
Fenton Avatar answered Nov 08 '22 11:11

Fenton