If I have an IIFE does this refer to the local scope?
(function(){
var $a;
$a = Su.$a
// this.$a = Su.$a; // can I replace with this
})();
I'm asking because I need Su.$a
available everywhere in my IIFE.
But I don't want to call Su.$a
, I want to call $a
.
is saying this.$a
the same as saying var $a
when var it top-level scoped?
If I have an IIFE does this refer to the local scope?
(function(){
var $a;
$a = Su.$a
// this.$a = Su.$a; // can I replace with this
})();
I'm asking because I need Su.$a
available everywhere in my IIFE.
But I don't want to call Su.$a
, I want to call $a
.
is saying this.$a
the same as saying var $a
when var it top-level scoped?
2 Answers
Reset to default 6No.
this
is set by a few things, described by MDN / this
Operator, but in short:
- the global object, at the top level scope
obj
, when executingobj.func(...)
obj
, when executingfunc.apply(obj, [...])
orfunc.call(obj, ...)
or the global object, ifobj
isnull
orundefined
- a new object with prototype
func.prototype
, when callingnew func(...)
- the event target, if
elem.addEventListener('event', func, ...)
andevent
is fired onelem
There's a few differences and additions in newer JavaScript, but that's pretty much it. this
is unrelated to function
scope.
No, they are different.
var $a
, then the $a
is local variable in the function scope.
But if you use this.$a
, because this is a self execution function, this
is window
in this case, this.$a
is same as window.$a
, so you are using a global variable $a
instead.