自执行函数
下面三个自执行函数是一样的
//1.
function test(i){
console.log(i)
}
test("aa")
//2.
(function(i){
console.log(i)
})('aa')
// 3.
var aa = "aa";
(function(i){
console.log(i)
})(aa)
var a = [1, 2, 3, 4]; {
var a = [1, 2, 3, 4, 5];
(function(i) {
var a = [1, 2, 3, 4, 5, 6];
for (var i = 0; i < a.length; i++) {
console.log(i) //0,1,2,3,4,5
}
})(a)
}
this
var num =1;
var obj = {
num:2,
fn:(function(num){
this.num*=2;
num+=2;
return function(){
this.num*=3;
num++;
console.log(num)
}
})(num) //window下的num
}
var fn = obj.fn;
fn(); //4
obj.fn() //5
console.log(num,obj.num); //6,6
fn()
console.log(fn)
console.log(obj.fn())
拆分
var num =1;
var obj = {
num:2,
fn:(function(num){
this.num*=2;
num+=2;
console.log(this) //window
return function(){
this.num*=3;
num++;
console.log(this) //window
console.log(num) //4
console.log(this.num) //6
}
})(num) //window下的num
}
var fn = obj.fn;
fn();
console.log(num,obj.num); //6,2
var num =1;
var obj = {
num:2,
fn:(function(num){
this.num*=2;
num+=2;
console.log(this) //window
return function(){
this.num*=3;
num++;
console.log(this) //obj
console.log(num) //4
console.log(this.num) //6
}
})(num) //window下的num
}
var fn = obj.fn;
obj.fn()
console.log(num,obj.num); //2,6
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。