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?
The global context (
windowin a browser) is the valuethisgets 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 withvar.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 (likesomething.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.