调用父级 "this" 作用域的外部函数

External function calling for parent's "this" scope

我有两个 .js 文件:root.js 和 external.js

root.js

import myExternalFunction from 'external.js'

class Parent {
    constructor(){}
    parentFunction = () => {
        console.log('I was called from an external function using "this."')
    }
}

external.js

export default myExternalFunction = () => {
    this.parentFunction()
}

目前我收到一个错误,关于它不是一个函数,或者无法访问 'this'。

如何导入想要使用调用它们的 'this' 作用域的外部函数?

How do I import external functions that want to use the 'this' scope from which they are being called?

这与您export/import函数的方式没有任何关系。

您需要考虑两件事:

  • 想要动态接收其 this 值的函数 ,因此请使用

    export default function myExternalFunction() {
        this.parentFunction()
    }
    
  • as usual,必须以正确的方式调用函数才能获得预期的 this 值。没有魔法可以将调用范围内的当前 this 值传递给被调用函数。你必须做类似

    的事情
    import myExternalFunction from 'external.js'
    
    class Parent {
        constructor(){
            this.method = myExternalFunction;
            this.parentFunction = () => {
                console.log('I was called from an external function using "this."')
            }
        }
    }
    
    const example = new Parent;
    example.method() // an invocation as a method
    myExternalFunction.call(example); // explicit using `call`