最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - 'this' inside an IIFE | Same as local scope? - Stack Overflow

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论