您的位置:首页 > Web前端 > JavaScript

JavaScript重构之立即执行函数

2016-11-19 12:56 363 查看
代码级优化,对于文件级的优化,立即执行函数是重中之重

参考:javascript立即执行某个函数:插件中function(){}()再思考

1.代码套路

1.基本套路

!function($){
// 在function中,$实际上就是jQuery,所以用$尽情玩耍吧。
}(jQuery);


2.更二套路

!function(fun){}(function($){});


这是很多插件的新套路:

下面是以兼容不同的加载模式(CommonJS、CMD、CMD)

!function(fun){
"use strict";
if(typeof define === 'function' && define.amd) {
define(['jquery'], fun)
} else {
fun((typeof(jQuery) != 'undefined') ? jQuery : window.Zepto)
}
}(function($){
"use strict";
// 真正的插件代码都在这里
});


3.最近见到新套路

(function(){}).call();


2.套路的好处

比较下面代码:

var timestamp = function(){
var timestamp = Date.parse(new Date());
return timestamp/1000;
}();


var timestamp = Date.parse(new Data());
timestamp = timestamp/1000;


看上去好像比上面的操作简洁多了,只需要两行代码。但是我们仔细去观察,就会发现第一段代码其实本身仅是一个赋值操作,在function中完成的所有动作将会在function执行完后全部释放,整个代码看上去好像只执行了一条语句一样。

3.难点(this问题)

匿名自执行函数中 this 指代为window

var age = 3;
var cat1 = new function() {
this.name = 'Tom';
this.age = 2;
this.weight = function(age) {
var age = age * 2;
var _age = this.age * 2; // 2   this指代的为window 难点
return 'weight by age:' + age + '; weight by this.age:' + _age;
}(this.age); // 1  这是一个匿名自执行函数 这个this表示cat1 this在cat1作用域里 难点
this.eye = new function() {
this.size = '1.5cm';
this.color = 'red'; // 3
};
this.catching = function(mouse) {
return this.name + ' is catching ' + mouse; // 4
};
};
console.log(cat1.weight);//weight by age:4; weight by this.age:6
console.log(cat1.eye.color);//red
console.log(cat1.catching('Jerry'));//Tom is catching Jerry
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript