zoukankan      html  css  js  c++  java
  • 箭头函数this的指向

    箭头函数的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
    
  • 相关阅读:
    JQ之html,text,val
    JQuery之编写弹窗
    DOM操作HTML元素属性
    DOM操作表格
    无缝滚动效果
    Date日期基础
    CISSP备考总结
    CISA考试大纲即将更新
    备考CISSP
    cisa备考体会
  • 原文地址:https://www.cnblogs.com/fitzlovecode/p/arrowFuncThis.html
Copyright © 2011-2022 走看看