问题:在setInterval和setTimeout中传入函数时,函数中的this会指向window对象

解决方法:

1. 将当前对象的this存为一个变量,定时器内的函数利用闭包来访问这个变量。var self = this;

2.利用bind绑定

setTimeout(function(){
   console.log(this.num);
}.bind(this), 1000) //利用bind()将this绑定到这个函数上

3. 箭头函数

setTimeout(() => {
    console.log(this.num);
}, 1000)    //箭头函数中的this总是指向外层调用者

 

参考:

http://www.cnblogs.com/zsqos/p/6188835.html

相关文章: