1、示例代码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>词法作用域</title>
</head>
<body>
<script type="text/javascript">
//方法一:self通过使用词法作用域和闭包
// var obj = {
// count:0,
// cool:function coolFn(){
// var self= this;
// if(self.count<1){
// setTimeout(function timer(){
// self.count++;
// console.log(self.count);
// },1000)
// }
// }
// };
//方法二:使用箭头函数
// var obj = {
// count:0,
// cool:function coolFn(){
// if(this.count<1){
// setTimeout(()=>{
// this.count++;
// console.log(this.count);
// },1000)
// }
// }
// };
//方法三:使用bind()
var obj = {
count: 0,
cool: function coolFn() {
if(this.count < 1) {
setTimeout(function timer() {
this.count++; //this是安全的,因为使用了bind
console.log(this.count);
}.bind(this), 1000)
}
}
};
obj.cool();
</script>
</body>
</html>
2、解决this绑定问题
(1)最常用的是方法一
(2)箭头函数:不够理想,函数是匿名的;同时混淆了this绑定规则和词法作用域规则。
var sum = (num1, num2) => (num1 + num2);
与
var sum = (num1, num2) => {return num1 + num2;}
效果一致。