Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways to define a method in TypeScript

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)

like image 523
Neil Barnwell Avatar asked Oct 25 '25 20:10

Neil Barnwell


1 Answers

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.

like image 64
Titian Cernicova-Dragomir Avatar answered Oct 28 '25 08:10

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!