typescrip中的绑定方法

2024-04-23 18:02:05 发布

您现在位置:Python中文网/ 问答频道 /正文

在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有一个类似的速记符号,即

^{pr2}$

您会使用lambda函数来生成类似Python中的“bound method”的闭包吗?还是有别的办法?在


Tags: andinstancelambda函数selfinitdef模式
1条回答
网友
1楼 · 发布于 2024-04-23 18:02:05

是的,您可以使用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);

也可以使用箭头函数来执行此操作:

^{pr2}$

相关问题 更多 >