JS的箭头函数this作用域

 

name="小刚";
let student={
    name:"小明",
    printLog:function(){
        // 这里绑定了顶层作用域,可以使用变量与方法
        console.log(this)
    },
    printArrowLog:()=>{
        // 这里不知道绑定的是哪个作用域,有知道的大咖请回答下
        console.log(this)
    }
}

student.printLog();
/*
    { name: '小明',
      printLog: [Function: printLog],
      printArrowLog: [Function: printArrowLog] 
    }
*/
student.printArrowLog();
/*
    {}
    这里返回了空对象,说明this不是指向window全局对象,也不是指向student对象。奇葩
*/

 

name="小刚";
let student={
    name:"小明",
    printLog:function(){
        // 这里绑定了顶层作用域,可以使用变量与方法
        return ()=>{
            console.log("printLog Arrow:"+this)
        }
    },
    printLog1:function(){
        // 这里绑定了全局作用域,可以使用window对象的属性
        return function(){
            console.log("printLog1:"+this)
        }
    },
    printLog2:function(){
        // 这里绑定了全局作用域,可以使用window对象的属性
        (function(){
            console.log("printLog2:"+this)
        })()
    }
}

sayhello=student.printLog();
sayhello1=student.printLog1();

sayhello();
/*
    printLog Arrow:小明
    this指向:printLog Arrow:[object Object]
    从这里我们可以看出这里使用的是student对象里的顶层属性,没有说明问题
*/

sayhello1();
/*
    printLog1:小刚
    this指向:printLog1:[object global]
    从打印的结果来看,我们可以看到打印的name值为小刚,是我在全局进行生命的name属性,说明在外部进行调用,this指向window全局对象

*/

student.printLog2();
/*
    printLog2:小刚
    this指向:printLog1:[object global]
    从打印的结果来看,我们可以看到打印的name值为小刚,是我在全局进行生命的name属性,说明生命调用写在一起,this指向window全局对象
*/

 

name="小刚";
let student={
    name:"小明",
    functions:{
        name:"小飞",
        printLog:function(){
            // 这里绑定了functions对象作用域,可以使用内部的变量与方法
            return ()=>{
                console.log("printLog:"+this.name)
            }
        },
        printLog1:function(){
            // 这里绑定了顶层作用域,可以使用window的变量与方法
            return function(){
                console.log("printLog1:"+this.name)
            }
        }
    }
}


var pl=student.functions.printLog();
pl();
/*
    printLog:小飞

*/


var pl1=student.functions.printLog1();
pl1();
/*
    printLog1:小刚
*/

/*总结:根据name的值不同,可以查到使用的是哪个作用域的值,进而可以知道this的指向*/

 

function方法调用call和apply的使用方式:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call

转载于:https://www.cnblogs.com/XingXiaoMeng/p/11437674.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值