zoukankan      html  css  js  c++  java
  • 箭头函数无法使用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>

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

  • 相关阅读:
    IO多路复用 IO异步
    你没听说过的协程
    事件驱动和IO操作
    堡垒机前戏——paramiko
    听说过的多进程,多线程到底是什么鬼
    socket套接字
    看见就烦的异常
    struts2值栈内部数据结构详解
    hibernate一级缓存的源码初窥
    使用自定义标签模拟jstl的<c:for each>标签
  • 原文地址:https://www.cnblogs.com/webBlog-gqs/p/7282707.html
Copyright © 2011-2022 走看看