网站搜索

Python - TypeScript 中的绑定方法


在 Python 中有一个常见的模式,其工作方式如下

class MyClass:
    def __init__(self):
        self._x = 0

    def increment_and_print(self, i):
        self._x = self._x + i
        print(self._x)

instance = MyClass()
bound_method = instance.increment_and_print

这里,bound_method 相当于一个函数 lambda i: instance.increment_and_print(i),也就是说,它像闭包一样包含了实例对象。

现在我想知道 TypeScript 是否有类似的简写符号,即

class MyClass {
  private _x : number;
  constructor() { this._x = 0; }
  incrementAndPrint(i: number) {
    self._x += i;
    console.log(self._x)
  }
}

你会只是使用 lambda 函数来生成类似 Python 中“绑定方法”简写的闭包吗?还是有其他方法?

答案#1

是的,你可以使用 bind 来做到这一点——函数在 JavaScript 中是一等公民,因此你可以很容易地传递它们:

class MyClass {
    private _x: number = 0;

    incrementAndPrint(i: number) {
        this._x += i;
        console.log(this._x)
    }
}

const myClass = new MyClass();

const incrementAndPrint = myClass.incrementAndPrint.bind(myClass);

incrementAndPrint(2);
incrementAndPrint(3);

你也可以用箭头函数来做:

const incrementAndPrint = (num: number) => myClass.incrementAndPrint(num);