【问题标题】:Access common value in call back in strict mode在严格模式下访问回调中的公共值
【发布时间】:2018-05-23 04:55:22
【问题描述】:

我在这样的回调中访问了公共值。

function InfoClass() {
    var local = 1;
    self = this;
}
InfoClass.prototype.myFunction = function (){
    this.win.addEventListener('open', function(e){
          // I can't use 'this' here. 
        self.local // So I access common value in callback like this.
    });
}

在严格模式之前它可以工作,

但是,现在我需要设置严格模式,所以它显示错误self 没有var

还有其他方法吗??

【问题讨论】:

  • 只需使用箭头函数,以便继承父作用域的this

标签: javascript strict


【解决方案1】:

您可以尝试关注

InfoClass.prototype.myFunction = function (){
    var self = this;
    this.win.addEventListener('open', function(e){
        self.local // you can access the function now
    });
}

或者你可以使用如下箭头函数

InfoClass.prototype.myFunction = function (){
    this.win.addEventListener("open", (e) => {
         this.local // you can use this now
    });
}

供参考,Arrow functions

【讨论】:

  • 哦,以后看起来对我来说真的很酷,我会学到更多。非常感谢mcuh
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多