回调函数中的this?

回调函数中的this指向?

回调函数中的this一般都是window,但是有特殊情况可以改变里面的this指向。
首先先看看什么是回调函数吧。

回调函数

回调函数:把一个函数作为值传递给另一个函数,再在另一个函数中把这个函数执行(这是实现函数式编程重要的知识)。

函数式编程:注重结果,不在乎过程,过程交给别人处理。
命令式编程:注重过程,且需要自己实现过程。

回调函数中的this:

首来看一个例子:

let obj = {
	i:0,
	func(){
		setTimeout(function(){
			this.i++;
			console.log(obj.i)  //i输出0
		},1000)
	}
}
obj.func();

上面的i为什么输出0呢?因为setTimeout中的回调函数中的this指向window,window中没有i。如果想改obj中的i值该怎么做呢?
方法一:将this值存起来

let obj = {
	i:0,
	func(){
	//this:obj
	let _this = this;  //将this的指向保存在_this中
		setTimeout(function(){
			//this:window, _this:obj
			_this.i++;
			console.log(obj.i)  //i输出1
		},1000)
	}
}
obj.func();

方法二:用bind把外面的this预先处理为obj

let obj = {
	i:0,
	func(){
	//this:obj
		setTimeout(function(){
			//this:obj 基于bind把函数中的this预先处理为obj
			this.i++;
			console.log(obj.i)  //i输出1
		}.bind(this),1000)
	}
}
obj.func();

方法三:用箭头函数
众所周知,箭头函数没有自己的this,它的this是继承所在上下文中的this!

let obj = {
	i:0,
	func(){
	//this:obj
		setTimeout(()=>{
			//this:obj 箭头函数没有this,用的this是上下文中的this,即obj
			this.i++;
			console.log(obj.i)  //i输出1
		},1000)
	}
}
obj.func();

猜你喜欢

转载自blog.csdn.net/Dracolan/article/details/107583633