我怎样才能使用这个内联函数并将其转换为方法,同时保留对此的访问权限?
How can I take this inline function and convert it to a method while retaining access to this?
我有一个 JavaScript class 具有这种结构:
class MyClass () {
myMethod() {
myCallback = (response) => {
// Do a bunch of stuff by referencing and altering properties in this
}
apiFunction(this.CLASS_PROP, myCallback);
}
}
myMethod
已经很长了,myCallback
的内容让它变得更长,所以我试着把它转换成这样的结构:
class MyClass () {
myMethod() {
apiFunction(this.CLASS_PROP, this.myCallback);
}
myCallback = (response) => {
// Do a bunch of stuff by referencing and altering properties in this
}
}
虽然第一个版本工作正常,但第二个版本失去了对 MyClass
实例的引用,而是 this
指向,我认为调用是 API实际上调用它。我不确定为什么,但我的理论是“词法上下文”并不意味着定义函数的位置,而是调用函数的位置。
但我的问题是,有没有办法将该函数从 myMethod
内部分解为 MyClass
的实例方法?
有很多种写法,其中一种是
class MyClass {
myMethod() {
apiFunction(this.CLASS_PROP, r => this._myCallback(r));
}
_myCallback(response) {
// Do a bunch of stuff by referencing and altering properties in this
}
}
请注意,在 apiFunction
中有一个箭头函数,而 _myCallback
是一个普通方法(=不是箭头)。反过来,就像在您的代码中一样,它不会起作用。
_myCallback
中的下划线表示私有方法(约定,不是特殊语法)
我有一个 JavaScript class 具有这种结构:
class MyClass () {
myMethod() {
myCallback = (response) => {
// Do a bunch of stuff by referencing and altering properties in this
}
apiFunction(this.CLASS_PROP, myCallback);
}
}
myMethod
已经很长了,myCallback
的内容让它变得更长,所以我试着把它转换成这样的结构:
class MyClass () {
myMethod() {
apiFunction(this.CLASS_PROP, this.myCallback);
}
myCallback = (response) => {
// Do a bunch of stuff by referencing and altering properties in this
}
}
虽然第一个版本工作正常,但第二个版本失去了对 MyClass
实例的引用,而是 this
指向,我认为调用是 API实际上调用它。我不确定为什么,但我的理论是“词法上下文”并不意味着定义函数的位置,而是调用函数的位置。
但我的问题是,有没有办法将该函数从 myMethod
内部分解为 MyClass
的实例方法?
有很多种写法,其中一种是
class MyClass {
myMethod() {
apiFunction(this.CLASS_PROP, r => this._myCallback(r));
}
_myCallback(response) {
// Do a bunch of stuff by referencing and altering properties in this
}
}
请注意,在 apiFunction
中有一个箭头函数,而 _myCallback
是一个普通方法(=不是箭头)。反过来,就像在您的代码中一样,它不会起作用。
_myCallback
中的下划线表示私有方法(约定,不是特殊语法)