首页 > 其他 > 详细

箭头函数this的指向

时间:2021-02-08 22:14:30      阅读:21      评论:0      收藏:0      [点我收藏+]

箭头函数的this

什么是箭头函数,箭头函数是es6的新特性,其出现就是为了更好的表示(代替)回调函数

// 箭头函数
(arg1, arg2) => {}
// 当箭头函数只有一个参数
arg1 => console.log(arg1)
// 箭头函数隐式return
arg1 => arg1  // 等价于  arg1 => return arg1

箭头函数的this不同于以上所有情况(不是在代码执行时确定),而是在箭头函数定义时确定的(类似于作用域),箭头函数的this就是其定义时的父级对象的this,如果父级对象也是个箭头函数,则继续向上找

var obj = {
        name: ‘Fitz‘,
        logObjThis: this,   // 打印obj的this
        test () {           // 测试一般情况的this
            console.log(this.name)
        },
        arrowFunc: () => {  // 测试箭头函数的this
            console.log(this)
        }
    }
name = ‘普通的this是根据执行时确定的‘
window.test = obj.test  // 将obj的test暴露给全局对象window
    

obj.test()  // Fitz
test()      // 普通的this是根据执行时确定的  等价于 window.test()

// 箭头函数的this是在箭头函数定义的时候确定的,就是箭头函数祖先对象的this
obj.arrowFunc()             // window   箭头函数的祖先对象是obj, obj的this是window
console.log(obj.logObjThis) // window  此语句等价于 window.obj.logObjThis

箭头函数this的指向

原文:https://www.cnblogs.com/fitzlovecode/p/arrowFuncThis.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!