2

主要关注的是效率。

我正在研究 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中。这对我有用。但它安全吗?它有效率吗?如果没有,请建议我一个好的策略/技巧。

谢谢 :)

4

1 回答 1

2

是的,它是安全的,但您可以使用新的箭头语法。它保留了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函数外部并在函数中使用别名。ES6里面有一个新的arrow syntax functionArrow functions不要覆盖this. 在你的情况下

run () {

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

thisin the和run functionin theparameter function是一样的。这意味着在 thearrow function scopethis 是指this在其中arrow function定义的。

在高效的情况下,您不需要额外的变量。您不会用额外的变量污染局部范围。在性能上没有影响。

于 2016-09-01T07:41:31.053 回答