admin管理员组

文章数量:1336140

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?

Share Improve this question edited Oct 24, 2012 at 16:37 hippietrail 17k21 gold badges109 silver badges179 bronze badges asked Aug 28, 2012 at 0:13 user656925user656925 0
Add a ment  | 

2 Answers 2

Reset to default 6

No.

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 executing obj.func(...)
  • obj, when executing func.apply(obj, [...]) or func.call(obj, ...)
    or the global object, if obj is null or undefined
  • a new object with prototype func.prototype, when calling new func(...)
  • the event target, if elem.addEventListener('event', func, ...) and event is fired on elem

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.

本文标签: javascript39this39 inside an IIFESame as local scopeStack Overflow