在匿名函数中使用 this 的有效解决方法是什么?

What is an efficient workaround for using this inside anonymous function?

主要关注的是效率。

我正在研究 javascript 作用域,我感到困惑的一件事是 this 函数内部。

我看了很多答案,我明白了。但我关心的是效率。看看我的代码。

  class Fancy {
    constructor () {
  }

  checkScope (callback) {
    console.log('Inside checkScope');
    callback ();
  }
}

class Prog {
  constructor () {
    this.name = 'myProg';
    this.fancy = new Fancy ();
  }

  run () {
    var that = this;
    this.fancy.checkScope(function () {
      console.log('Name ', that.name);
    });
  }
}

var prog = new Prog ();
prog.run();

现在 run() 我将 this 的引用存储在局部变量 that 中。这对我有用。但它安全吗?有效率吗?如果没有,请给我推荐一个好的strategy/trick.

谢谢:)

是的,它是安全的,但您可以使用新的 arrow syntax。它保留了 this

 class Fancy {
    constructor () {
  }

  checkScope (callback) {
    console.log('Inside checkScope');
    callback ();
  }
}

class Prog {
  constructor () {
    this.name = 'myProg';
    this.fancy = new Fancy ();
  }

  run () {
    // Here your don't need var that = this, 
    // because the arrow function gets the same this
    this.fancy.checkScope( () => {
      console.log('Name ', this.name);
    });
  }
}

var prog = new Prog ();
prog.run();

每个简单函数都有它的 this,在您的情况下是您的

 function () {
      console.log('Name ', this.name); // this is undefined in 'strict mode'
    }

有自己的this。所以你需要把this保留在函数外面,在function.InES6中使用with alias有一个新的arrow syntax function.Arrow functions 不要覆盖 this。你的情况

run () {

        this.fancy.checkScope( () => {
          console.log('Name ', this.name);
        });
      }

run functionparameter function中的this是一样的。这意味着在 arrow function scopethis 指的是 this 其中定义了 arrow function

在高效的情况下,你不需要额外的variable.You不要用额外的变量污染局部作用域。在性能上没有任何影响。