nextdoordoc nextdoordoc - 1 year ago 65
AngularJS Question

what is the meaning of this? setTimeOut(() =>, 0)

I am practicing angularjs2 and I notice this sentence but cannot understand what this means.

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, '', ''); = false;
setTimeOut(()=>, 0)*


I know in JavaScript there is a function name
but cannot understand the
and arrow

Thanks in advance!

Answer Source

This is the new JavaScript arrow function notation (also known as lambda in some other languages).

The line you quoted is equivalent to this piece of code in the traditional JavaScript notation:

setTimeout(function() { = true;
}, 0);

However, this will be bound to the global object (outside of strict mode - in strict mode, you will get a ReferenceError) in this code, due to how binding of this in execution contexts works. The traditional workaround before the introduction of arrow functions would be:

var self = this;
setTimeout(function(){ = true;
}, 0)

Arrow functions solve this problem by lexically binding this, just as any other variable, instead of defining their own.

Besides this,arrow functions do not define their own arguments or supervariables either but bind them lexically.

Digging deeper, what does newHero() do? It is a constructor function. When you call it, a new object is allocated, and it can be referred to within the function body by the variable this. The constructor sets two properties on the this object; these properties are .model and .active, being given specific values.

The expression (() => = true) creates a function object. It describes what should execute at a later time. When the function object is called, the body gets executed. So the line of code creates the function object and gives it to setTimeout(), which will call the function object after the given length of time - in this case, 0 milliseconds.