作为参数给出时如何保持函数上下文

问题描述 投票:0回答:1

复制

this.xxx
函数时,似乎丢失了某种上下文。

在以下示例中,对

this.post
的调用工作正常,但
postCopy
会导致错误。

class MyClass {
  
  myFunc(){
    await this.post(...) // works fine

    const postCopy = this.post
    await postCopy(...) // does not work properly
  }
}

我不明白这两个调用有什么区别,因为

postCopy === this.post
=>
true

我的最终目标是把

this.post
作为
myFunc
的论据,我怎样才能实现让
postCopy
正常工作?

javascript node.js this
1个回答
0
投票

当调用命名函数时,(const/let/parameter),

this
上下文不会被传递,除非你使用
postCopy.call(this, ...args)

© www.soinside.com 2019 - 2024. All rights reserved.