Different ways to define a method in TypeScript

2020-04-14 12:12发布

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)

1条回答
smile是对你的礼貌
2楼-- · 2020-04-14 12:54

The difference in functionality occurs when you use this in the function and you pass that function to someone else. Normal functions do not capture this from the context where they were declared, while arrow functions do. If you assign a normal function to a variable and call it this will not be an instance of Screen1

class Screen1 {
    msg = "Hello"
    method1(arg: string): string {
        return this.msg;
    }

    method2 = (arg: string): string => {
        return this.msg;
    };
}

var v = new Screen1();
var fn = v.method1;
fn(""); // will return undefined
var fn2 = v.method2;
fn2(""); // will return "Hello"

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.

查看更多
登录 后发表回答