function obj() { this.fn = function() { alert("ok"); console.log(this); setTimeout(this.fn.bind(this), 1000);//通过Function.prototype.bind 绑定当前对象 } } var o = new obj(); o.fn();
// 方法三: function obj() { this.fn = function() { var that = this;//保存当前对象this alert("ok"); setTimeout(function(){ that.fn(); }, 1000);//通过闭包得到当前作用域,好访问保存好的对象that } } var o = new obj(); o.fn();
上面第三个方法的两个关键点是 保存当前对象this为别名that 和 通过闭包得到当前作用域,以访问保存好的对象that;当对象方法里面多层嵌套函数或者setTimeout,setInterval等方法丢失this(也就是this不指向当前对象而是window),所以在this指向正确的作用域保存var that = this就变得很实用了