(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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With