Typescript + AngularJs Bug?

Topics: General, Language Specification
Jul 4, 2014 at 9:50 AM
Hello,

today i wanted to write an Angular app and there is one thing i don't understand.
myApp.service("myMath",()=> {
    alert("service created");
    this.sayHello = () => {
        alert("hello");
    }
});
this snipped compiles into:
myApp.service("myMath", function () {
    alert("service created");
    _this.sayHello = function () {
        alert("hello");
    };
});
and this snipped:
myApp.service("myMath",function(){
    alert("service created");
    this.sayHello = () => {
        alert("hello");
    }
});
compiles to:
myApp.service("myMath", function () {
    alert("service created");
    this.sayHello = function () {
        alert("hello");
    };
});
The difference is, that in the first example, it compiles into _this and then the code won't run correctly.
Can anyone explain me, why this is so?

Many thanks in advance, cristan.
Jul 4, 2014 at 12:15 PM
The difference is that the first example is using the lambda/arrow function syntax which captures the "this" context.
See more about the ES6 feature on Mozilla here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/arrow_functions
Jul 7, 2014 at 7:29 AM
Thank you for the reply.
I understand, i always thought, that the arrow function is only a other syntax for the normal function.
Jul 21, 2014 at 5:51 AM
@cristan I did a video on it : https://www.youtube.com/watch?v=tvocUcbCupA&hd=1 if you are interested
Jul 22, 2014 at 8:35 PM
@basarat, thank you for your reply. I have already seen all your videos about typescript and angular, but i think i overlooked that video. It would have saved me a lot of time.