我看到很多代码,例如:
var myApp ={};
(function() {
console.log("Hello");
this.var1 = "mark"; //"this" is global, because it runs immediately on load. Caller is global
myApp.sayGoodbye = function() {
console.log("Goodbye");
};
})();
这会导致匿名函数立即执行。但是,与仅将代码内联相比,这样做的优势是什么?
var myApp ={};
console.log("Hello");
var1 = "mark";
myApp.sayGoodbye = function() {
console.log("Goodbye");
};
显然它与函数的范围有关,但是由于该函数是匿名的并且由窗口调用,所以它的范围(即this
)是全局的,不是吗?