这是什么意思?setTimeOut(()=> this.active = true,0)

nex*_*doc 3 javascript angularjs

我正练习angularjs2,我注意到这句话,但无法理解这意味着什么.

@Component({
    selector: 'hero-form',
    templateUrl: 'app/hero-form.component.html'
})

export class HeroFormComponent {

    model = new Hero(18, 'Dr IQ', this.powers[0], 'Chuck Overstreet');

    active = true;

    newHero() {
        this.model = new Hero(42, '', '');
        this.active = false;
        setTimeOut(()=> this.active=true, 0)*
    }

}
Run Code Online (Sandbox Code Playgroud)

我知道在JavaScript中有一个函数名称,setTimeOut但无法理解()和箭头=>......

提前致谢!

Nay*_*uki 14

这是新的JavaScript 箭头函数表示法.您引用的行几乎等同于传统函数表示法中的这段代码:

setTimeout(function() {
    this.active = true;
}, 0);
Run Code Online (Sandbox Code Playgroud)

但是在传统的表示法中,this将绑定到全局对象(在严格模式之外 - 在严格模式下,你会得到一个ReferenceError),由于这在执行上下文中如何绑定起作用.在引入箭头函数之前的传统解决方法是:

var self = this;
setTimeout(function() {
    self.active = true;
}, 0)
Run Code Online (Sandbox Code Playgroud)

箭头函数通过词法绑定解决此问题this,就像任何其他变量一样,而不是定义自己的变量.除了如何this处理之外,箭头函数也不会隐式定义它们自己argumentssuper变量,而是以词法方式绑定它们.


深入挖掘,做newHero()什么?它是一个构造函数.调用它时,会分配一个新对象,并且可以通过变量在函数体内引用它this.构造函数在this对象上设置两个属性; 这些属性是.model.active,具有特定的值.

表达式(() => this.active = true)创建一个函数对象.它描述了以后应该执行的内容.调用函数对象时,将执行正文.因此,代码行创建了函数对象并将其赋予setTimeout(),它将在给定的时间长度之后调用函数对象 - 在本例中为0毫秒.