Different ways to define a method in TypeScript

前端 未结 1 1256
粉色の甜心
粉色の甜心 2021-01-22 11:22

I have a module in TypeScript as follows:

import app = require(\"durandal/app\");
import ko = require(\"knockout\");

class Screen1 {
    method1(arg: string): s         


        
相关标签:
1条回答
  • 2021-01-22 11:36

    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.

    0 讨论(0)
提交回复
热议问题