简体   繁体   English

打字稿成员函数最佳实践

[英]Typescript member function best practice

While reading about the this keyword in typescript and the fat arrow operator I came across an example that makes me wonder what is the best way to declare a member method in a class? 在阅读打字稿中的this关键字和粗箭头运算符时,我遇到了一个示例,这使我想知道在类中声明成员方法的最佳方法是什么?

Essentially, is there a difference between this: 本质上,这之间是有区别的:

class MyClass {
    private status = "blah";

    public run = () => { // <-- note syntax here
        alert(this.status);
    }
}

And this: 和这个:

class MyClass {
    private status = "blah";

    public run() {
        alert(this.status);
    }
}

?

If you declare a normal function: 如果声明一个正常函数:

public run() { /*...*/ }

It will be declared on prototype: 它将在原型上声明:

MyClass.prototype.run = function () { /*...*/ };

However, if you declare a fat arrow function: 但是,如果您声明粗箭头功能:

public run2 = () => { /*...*/ }

It will be declared on every instance of your class AND will be bound to this class. 它会在您的类的每个实例上声明,并且将绑定到该类。

function MyClass() {
    this.run2 = function () { /*...*/ };
}

Now consider this: 现在考虑一下:

class MyClass {
    private status = "blah";

    public run() {
        alert(this.status);
    }
    public run2 = () => {
        alert(this.status);
    }
}
var obj = new MyClass();
obj.run(); // alerts 'blah'
obj.run2(); // alerts 'blah'
var p = { run: obj.run, run2: obj.run2 };
p.run(); // alerts 'undefined'
p.run2(); // alerts 'blah'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM