Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

javascript - IIFE context issues

In the following construct:

(function(){

    var x = function(){
        alert('hi!');
    }

    var y = function(){
        alert("hi again!");
    }

    this.show = function(){
        alert("This is show function!");
    }

})();

Why does this refer to window object? Should everything inside IIFE be isolated from global scope? Are x and y functions also properties of window global object?

Also, even if I use put var h = ... at the beginning:

var h = (function(){

    var x = function(){
        alert('hi!');
    }

    var y = function(){
        alert("hi again!");
    }

    this.show = function(){
        alert("This is show function!");
    }

})();

this still refers to window object -- I can just call show() from the global scope! How come?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The global context (window in a browser) is the value this gets when there's no other value to use.

Your local variables are local (that is, not properties of window). They're declared inside the function with var.

The reason why adding var h = (function(){... makes no difference is because of the way you call the function. The function reference is not a property value of an object (like something.func()), and you don't invoke it with .call() or .apply(), so therefore this refers to the global (window) object. That's just the way the language is defined to act.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...