对于闭包的痛点在于,闭包的this默认绑定到window对象,但又常常需要访问嵌套函数的this,所以常常在嵌套函数中使用var that = this,然后在闭包中使用that代替this,使用作用域查找的方法来找到嵌套函数的this值。
var a = 0;
functionfoo(){functiontest(){
console.log(this.a);
}
return test;
};
var obj = {
a : 2,
foo:foo
}
//obj.foo()执行的结果是返回test函数引用,所以obj.foo()()实际上是在全局环境中执行test函数。
obj.foo()();//0
解决办法
var a = 0;
functionfoo(){var that = this; //这个this指的是obj,因为foo函数是被当做方法调用的。functiontest(){
console.log(that.a);
}
return test;
};
var obj = {
a : 2,
foo:foo
}
obj.foo()();//2
var test = () => {
console.log(this.a);
}
//形式上等价于var test = function(){
console.log(this.a);
}
//实质上等价于functionfn(){var that = this;
var test = function(){
console.log(that.a);
}
}
var a = 0;
function foo(){
vartest = () => {
//通过箭头函数定义时,相当于执行了 that = this的操作,然后在内部使用的是that
console.log(this.a);
}
return test;
};
var obj = {
a : 2,
foo:foo
}
obj.foo()();//2
二、基本用法
ES6允许使用“箭头函数”(=>)定义函数,一般称为胖箭头
//这定义了只有一个参数的箭头函数var f = v => v;
console.log(f(1));//1//等同于var f = function(v) {return v;
};
console.log(f(1));//1
如果箭头函数不需要参数或者需要多个参数,就要使用一个圆括号代表参数部分。
var f = () => 5;
// 等同于var f = function() {return5 };
var sum = (num1, num2) => num1 + num2;
// 等同于var sum = function(num1, num2) {return num1 + num2;
};