dev*_*raj 3 javascript ecmascript-6 babeljs
我正在搜索,找不到以ES6方式弄清楚这一点的正确方法.
class MyClass {
  // i can't event decalre _this/_self here
  constructor() {
     setTimeout(function(){
        // other work..
        hiUser(); // this.hiUser() or //_this.hiUser() not working
     },1000);
   }
   hiUser(){
     alert('Hi');
   }
}
ndu*_*ger 10
以前的答案只给出了如何解决它的代码示例; 让我解释一下你的问题及其发生的原因
在代码例如,你的setTimeout的内部的功能被结合到this所述的setTimeout的值(其通常是window或undefined在严格模式).
setTimeout(function () {
    // this === window
}, 1000);
在ES6中,他们引入了" 词法绑定 "的lambda表达式(箭头函数)- 这意味着他们从外部范围借用了值.在你的情况下,这是类/对象.this
为了利用lambda表达式 s,它看起来像:
class Foo {
    constructor () {
        setTimeout(() => this.myMethod(), 1000);
    }
    myMethod () {
        console.log('foo');
    }
}
如果您使用Babel来转换代码并使用实验性功能,则可以使用ES7的绑定语法来解决您的问题.
如果绑定一个函数/方法,它会创建该函数的副本,并将this值绑定到您选择的任何值.这将允许您使用function将绑定到您的类/对象的语句.
<context to be bound> :: <function to receive context>
class Foo {
    constructor () {
        setTimeout(this::function() {
            this.myMethod();
        }, 1000);
    }
    myMethod () {
        console.log('foo');
    }
}
更短的版本看起来像下面这样
constructor () {
    setTimeout(this::this.myMethod, 1000);
}
如果你仍然有理解这个问题,我建议你阅读更多关于ES6类和javascript绑定的内容.
| 归档时间: | 
 | 
| 查看次数: | 1183 次 | 
| 最近记录: |