ES6 中箭头函数 this 指向问题

在上一讲当中,我们知道了es5 中函数的 this 指向问题,即:指向直接调用它的那个对象。那么,在es6 中,箭头函数中的 this 指向是不是会有所不同呢?答案是必然的,今天我们就来聊聊箭头函数的this指向~

首先来简单对比一下:

【es5普通函数】

// es5:
var str = 'window'

var obj = {
	str: 'obj',
	fn: function () {
		console.log(this.str)
	}
}

obj.fn()  // obj

【es6箭头函数】

var str = 'window'

var obj = {
	str: 'obj',
	fn: () => {
		console.log(this.str)
	}
}

obj.fn()  // window

在 es5 中,this 的出身并不能决定他这辈子永远指向谁,而是要看最终谁直接调用他;

在 es6 中,箭头函数 this 指向的对象在出世的那一刻,就已经能确定下来了。即:指向他所处对象所在的作用域

var str = 'Global'
var obj = {
	str: 'obj',
	fn: function () {
		var str = 'zhangsan'
		this.name = 'edward'
        
		console.log(this.str)  // obj
		
		return {
			str: 'newObj',
			fn: () => {
				console.log(this.str)  // obj   
				console.log(this.name) // edward
			}
		}
	}
}

var newObj = obj.fn() 
newObj.fn()    

  

猜你喜欢

转载自www.cnblogs.com/edwardwzw/p/11706833.html