I have a module in TypeScript as follows:
import app = require("durandal/app");
import ko = require("knockout");
class Screen1 {
method1(arg: string): string {
return "Hello";
}
method2 = (arg: string): string => {
return "Hello";
};
}
export = Screen1;
This generates the following JavaScript:
define(["require", "exports"], function (require, exports) {
"use strict";
var Screen1 = (function () {
function Screen1() {
this.method2 = function (arg) {
return "Hello";
};
}
Screen1.prototype.method1 = function (arg) {
return "Hello";
};
return Screen1;
}());
return Screen1;
});
I can see the different output for each method, but what is the actual practical difference at runtime? I suspect it's going to affect what this
would mean if used in those methods, but I'm not sure the best way to investigate that.
(One of the most frustrating things with TypeScript for me is how many ways there are to do seemingly the exact same thing, with incomprehensibly subtle differences - like defining a class, for instance. I know 4 ways to do so. Very confusing)
The difference in functionality occurs when you use
this
in the function and you pass that function to someone else. Normal functions do not capturethis
from the context where they were declared, while arrow functions do. If you assign a normal function to a variable and call itthis
will not be an instance ofScreen1
There is also a performance implication. Since normal functions are assigned to the prototype they are only created once. Arrow functions have to capture
this
and thus have to be created for every instance of the class. If you insatiate may objects this may be a problem.