javascript - setInterval behaviour in TypeScript -
i started play around typescript. i´ve created sample project visual studio 2012 express web , sample has line of code has behaviour cannot explain myself.
first typescript code:
start() { this.timertoken = setinterval(() => this.span.innerhtml = new date().toutcstring(), 500); }
so line sets value of timertoken every 500ms , updates html element current date/time.
in javascript equivalent this:
greeter.prototype.start = function () { this.timertoken = setinterval(this.span.innerhtml = new date().toutcstring(), 500); };
so wondered lambda expression in typescript code line , removed date/time string won't updated anymore.
so easy question ... why?
i assuming span
property in same class start
method... correct me if wrong on this.
so fat-arrow syntax has special meaning in typescript.
when use () =>
typescript preserves lexical scope... means this
means same inside expression outside of expression. can see in compiled javascript creates variable named _this
that.
so fat-arrow syntax, this.span
property named span on class. without fat-arrow syntax, this.span
undefined.
you can use basic test see difference calling withfatarrow
or withoutfatarrow
, you'll see happens.
class test { public example = 'test'; private timer; withfatarrow() { this.timer = settimeout(() => alert(this.example), 500); } withoutfatarrow() { this.timer = settimeout(function() { alert(this.example) }, 500); } } var test = new test(); //test.withfatarrow(); test.withoutfatarrow();
Comments
Post a Comment