在TypeScript中定义方法的不同方法 [英] Different ways to define a method in TypeScript

查看:199
本文介绍了在TypeScript中定义方法的不同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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;

这会生成以下JavaScript:

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.

(TypeScript对我来说最令人沮丧的事情之一就是有多少种方法看似完全相同的事情,具有难以理解的细微差别 - 例如定义一个类。我知道4种方法这样做。非常令人困惑)

(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)

推荐答案

使用这个在函数中,您将该函数传递给其他人。正常函数不会从声明它们的上下文中捕获这个,而箭头函数则可以。如果为变量分配一个普通函数并将其命名为,则将不是 Screen1的实例

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.

这篇关于在TypeScript中定义方法的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆