ES6中箭头函数的this指向和注意事项

先说结论:

  • 箭头函数this指向:
    • 箭头函数没有this指向,箭头函数内部的this只能通过查找作用域链来确定
  • 箭头函数使用注意事项:
    • 使用箭头函数,函数内部没有arguments
    • 箭头函数不能使用new 关键字来实例化对象。

箭头函数this指向 例子:

        let pageHandle = {
            id:123,
            init:function(){
                document.addEventListener('click',function(){
                	console.log(this)
                    this.do(event.type)
                },false)
            },
            do:function(type){
                console.log(`点击事件类型:${type},当前id:${this.id}`)
            }
        }
        pageHandle.init()
打印结果: #document
报错信息:
es6.html:14 Uncaught TypeError: this.do is not a function
    at HTMLDocument.<anonymous> (es6.html:14)

我们看到里面打印的this是document,所以下边打印this.do(event.type)就会报错。我们可以这样修改

        let pageHandle = {
            id:123,
            init:function(){
                document.addEventListener('click',(event)=>{
                    console.log(this)
                    this.do(event.type)
                },false)
            },
            do:function(type){
                console.log(`点击事件类型:${type},当前id:${this.id}`)
            }
        }
        pageHandle.init()
       打印结果:
       {id: 123, init: ƒ, do: ƒ}
       点击事件类型:click,当前id:123

因为箭头函数没有this指向,所以this的值要向上一层作用域链

箭头函数使用注意事项 例子:
1.箭头函数内部没有arguments

	    let getVal = (a,b) => {
            console.log(arguments)
            return a + b
        }
        console.log(getVal(1,3))
 运行结果:报错
 Uncaught ReferenceError: arguments is not defined
    at getVal (es6.html:24)
    at es6.html:27

2.箭头函数不能使用new关键字实例化对象

	let person = ()=>{
	}
	//注:function函数也是一个对象,但是箭头函数不是一个函数,他其实是一个语法糖
	let p = new Person()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值