gpt4 book ai didi

javascript - 第三方库正在绑定(bind)回调,但我需要访问类属性

转载 作者:行者123 更新时间:2023-11-30 09:32:51 26 4
gpt4 key购买 nike

我看到了几个关于在类和函数中使用“this”的问题,但我认为我没有看到我特别要找的东西。

我的情况是:

我在类方法中调用第三方库中的函数。但是,第三方库函数正在调用 callback.bind(this),我需要访问它绑定(bind)的上下文。

但我也希望能够访问类属性。这可能吗? 如果没有,有哪些潜在的解决方法?代码大纲类似于:

class MyClass {
myProperty = 'something';

myMethod() {
console.log(this.myProperty);
}

otherMethod() {
thirdPartyLibrary.functionRequiringCallback(function() {
this.MyMethod(); //undefined
this.requiredThirdPartyFunction(); //"this" refers to thirdPartyLibrary
});
}
}

我当然可以将回调设为箭头函数,以便“this”引用类作用域,但那样我就无法访问“requiredThirdPartyFunction”。

如有任何帮助,我们将不胜感激。

最佳答案

当你想要引用你的实例 this 时,你总是可以使用旧的 that = this任务。您将 this 分配给作用域中的一个变量(通常是 that),然后您可以在回调中引用它。

otherMethod() {
const that = this; // set a reference to the instance this

thirdPartyLibrary.functionRequiringCallback(function() {
that.MyMethod(); // that refers to your class instance this
this.requiredThirdPartyFunction(); //"this" refers to thirdPartyLibrary
});
}

另一种选择是使用箭头函数或 Function#bind 绑定(bind) myMethod,然后将绑定(bind)的方法分配给变量:

class MyClass {
myProperty = 'something';

myMethod = () => console.log(this.myProperty);

otherMethod() {
const myMethod = this.myMethod; // assign the bound method to a variable

thirdPartyLibrary.functionRequiringCallback(function() {
MyMethod(); // will be invoked with original this
this.requiredThirdPartyFunction(); //"this" refers to thirdPartyLibrary
});
}
}

关于javascript - 第三方库正在绑定(bind)回调,但我需要访问类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45270214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com