箭头函数和匿名函数的this指向问题

之前一直认为箭头函数和匿名函数很相像,只知道他们的this指向有所不同,但到具体环境中还是不明白箭头函数指向哪里,抽空自己试了一下,可以更好的理解箭头函数的指向。

箭头函数的this:

        箭头函数没有自己的this指向,所谓的this是捕获其所在上下文的this作为自己的this,它没有prototype原型,所以没有this。在定义箭头函数时,this继承自外层第一个普通函数的this。一般指向window。

        箭头函数不绑定arguments参数,参数可以用 ...arg代替。

 下面是我理解箭头函数时的示例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
    console.log("----------a---------");
    var a = function(){
    console.log("将匿名函数赋值给变量a",a.prototype) // constructor:f
    console.log(this); // 指向全局变量Window
    return this
}
a()

console.log("------------b---------");
var b = ()=>{
    console.log("将箭头函数赋值给变量b",b.prototype); // undefined
    console.log(this); // 指向Window
    return this
}
b()

console.log("--------------c-------------");
var c = {
    x:23,
    y:function() {
        console.log("obj中的匿名函数");
        console.log(this); // {x: 23, y: ƒ, z: ƒ, f: ƒ} 
    },
    z:()=>{
        console.log("obj中的箭头函数",);
        console.log(this); // 指向Window
    },
    f:function(){
        var n=1;
        (()=>{
            console.log(this); // {x: 23, y: ƒ, z: ƒ, f: ƒ}
        })()
    }
        // 箭头函数继承自外层普通函数的this指向

}
c.y()
c.z()
c.f()

    </script>
</body>
</html>

值得注意的是,在对象中,如果箭头函数直接赋值给对象变量,其this指向window,但如果被函数包裹(c.j),箭头函数的this与普通函数指向相同(c.y())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值