ES6 中箭头函数 this 指向问题-------【附:window全局方法】

在上一讲当中,我们知道了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()    

 

setTimeout/ setInterval 回调函数中 this 指向问题的解决办法:

 

var obj = {        
    x:100,
    detail() {
        setTimeout(function(){
           console.log(this.x)
        },1000)
    }
};
obj.detail(); // undefined  

 

先来看上面的这个例子,我们的本意是想要在obj.detail() 处延迟1秒打印this.x,从而打印100。但结果却打印出了 undefined。

x的值确实是100,问题出在了this上,当代码执行到了setTimeout( )的时候,此时的this已经变成了window对象(setTimeout( )是window对象的方法),已经不再是obj对象了,ES5中可以用var that = this的方式避免。

 

 【方法一】:es5   var  that = this

var obj = {        
    x:100,
    detail() {
        var that = this;     
        setTimeout(function(){
           console.log(that.x)
        },1000)
    }
};
obj.detail(); // 100

 【方法二】:es6  箭头函数

var obj = {        
    x:100,
    detail() {    
        setTimeout(() => {
           console.log(this.x)
        },1000)
    }
};
obj.detail(); // 100
箭头函数中的this总是指向外层调用者,也就是obj
 
 
-------------------------------
 
【附件】:

window对象的全局方法

1、window.alert(‘嘿’):显示带有一段消息和一个确认按钮的警告框。

2、window.prompt():显示可提升用户输入的对话框

3、window.confirm():显示带有一段消息,以及确认按钮和取消按钮的对话框

4、window.focus():把键盘焦点给予一个窗口。

5、window.blur():把键盘焦点从顶层窗口移开

6、window.close():关闭浏览器窗口

7、window.open():打开一个新的浏览器窗口或查找一个已命名的窗口

8、window.setTimeout():在指定的毫秒数后调用函数或计算表达式

9、window.clearTimeout();取消由 setTimeout() 方法设置的 timeout。

10、window.setInterval():按照指定的周期(以毫秒计)来调用函数或计算表达式。

11、window.clearInterval():取消由 setInterval() 设置的 timeout

12、window.scrollBy():按照指定的像素值来滚动内容

13、window.scrollTo():把内容滚动到指定的坐标

14、window.moveBy():可相对窗口当前的坐标,移动指定的像素

15、window.moveTo():把窗口的左上角移动到指定的坐标

16、window.resizeBy():按照指定的像素,调整窗口的大小

17、window.resizeTo():吧窗口的大小调整到指定的宽度和高度

18、window.print():打印当前窗口的内容

19、window.creatPopup():创建一个pop-up窗口
 

posted @ 2019-10-20 10:22  牧羊狼  阅读(1102)  评论(0编辑  收藏  举报