箭头函数无法使用this的解决方法

ES6中箭头函数  () => { }  ,看到这么简单的写法,我也是很喜欢用的。但是如果想在箭头函数里面使用this,那么就会出现获取不到当前对象,而是获取到window对象。

 

下面这个是ES5中原型链上添加了一个say函数,在函数内打印出this对象,运行后能够得到正确    Person {name: "小米", age: 7}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>箭头函数与this</title>
</head>
<body>
    <script>
        function Person(name,age){
            this.name = name;
            this.age = age;
        }
        Person.prototype.say = function(){
            console.log(this);
        }
        var xiaomi = new Person('小米',7);
        xiaomi.say();  //Person {name: "小米", age: 7}
    </script>
</body>
</html>

 

好了,那么如果使用箭头函数呢,这里直接将say改成箭头函数。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>箭头函数与this</title>
</head>
<body>
    <script>
        function Person(name,age){
            this.name = name;
            this.age = age;
        }
        Person.prototype.say = () => {
            console.log(this);
        }
        var xiaomi = new Person('小米',7);
        xiaomi.say(); // window
    </script>
</body>
</html>

打印出来的this直接显示是window对象,这显然不符合要求,为什么会变成window对象呢,原因是箭头函数这个  =>  后面的这个花括符( { } )不是一个function作用域

那么到这里应该如何去获得,这里采用缺啥补啥的方法(将缺少的对象传入)--简单粗暴但有效。

 

2018-03-20   22:54:23

这里补充关于箭头函数里面this 在上面为什么是window的原因:

因为箭头函数是不具备this的,虽然你也可以使用this这个关键字,不过这个this指的是他的最接近的上下文环境,故这里的this指向window

2018-03-20  22:56:11

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>箭头函数与this</title>
</head>
<body>
    <script>
        function Person(name,age){
            this.name = name;
            this.age = age;
        }
        Person.prototype.say = (self) => {
            console.log(self);
        }
        var xiaomi = new Person('小米',7);
        xiaomi.say(xiaomi); // Person {name: "小米", age: 7}
        xiaomi.food = '面包';
        Person.prototype.eat =(self) =>{
            console.log(self.name + '正在吃' + self.food);
        }
        xiaomi.eat(xiaomi); //小米正在吃面包
    </script>
</body>
</html>

 

所以看到这里,知道箭头函数的局限性后,建议减少使用箭头函数,避免出现不必要的错误。

 

转载于:https://www.cnblogs.com/webBlog-gqs/p/7282707.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值