美文网首页
箭头函数中this

箭头函数中this

作者: AAA前端 | 来源:发表于2019-04-17 14:52 被阅读0次

    不绑定this

    箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this

    来自mdn

    • 在箭头函数出现之前,每个新定义的函数都有它自己的this值(在构造函数的情况下是一个新对象,在严格模式的函数调用中为 undefined,如果该函数被作为“对象方法”调用则为基础对象等)。This被证明是令人厌烦的面向对象风格的编程。
    age = 10;
    
    function Person() {
        // Person() 构造函数定义 `this`作为它自己的实例.
        this.age = 0;
      
        setTimeout(function growUp() {
          // 在非严格模式, growUp()函数定义 `this`作为全局对象, 
          // 与在 Person()构造函数中定义的 `this`并不相同.
          this.age++;
          console.log(this, this.age)
        }, 100);
      }
      
      var p = new Person();
    
    
    image.png
    • 在ECMAScript 3/5中,通过将this值分配给封闭的变量,可以解决this问题。
    age = 10;
    
    function Person() {
        var that = this;
        this.age = 0;
      
        setTimeout(function growUp() {
          that.age++;
          console.log(that, that.age)
        }, 100);
      }
      
      var p = new Person();
    
    
    image.png
    • 箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this。因此,在下面的代码中,传递给setInterval的函数内的this与封闭函数中的this值相同:
    age = 10;
    
    function Person() {
        this.age = 0;
      
        setTimeout(() =>{
          this.age++;
          console.log(this, this.age)
        }, 100);
      }
      
      var p = new Person();
    
    image.png

    参考: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    相关文章

      网友评论

          本文标题:箭头函数中this

          本文链接:https://www.haomeiwen.com/subject/utlnwqtx.html