我试图弄清楚如何完成以下任务。我希望能够调用另一个文件中的类中的函数:
file1
export class Something {
constructor() {
...
}
myFunction = () => {
...
}
}
file2
import { Something } from 'file1';
export function theFunction() {
if (condition met) {
Something.myFunction(...) // The myFunction is saying it's not a function
}
}
答案 0 :(得分:1)
class Canonical { /* in ES5 */ function Canonical() {}
myMethod() { ... } Canonical.prototype.myMethod = function() { ... };
}
您可以这样称呼:
Canonical.prototype.myMethod();
// Or, to call it as a method on anObject
Canonical.prototype.myMethod.call(anObject);
但是您创建的不是方法,而是在每个实例上创建的属性,恰好是一个函数:
class Unusual { /* in ES5 */ function Unusual() {
myFunction = () => { ... }; this.myFunction = function() { ... };
} }
它仅存在于实例上,因此您必须创建一个实例来调用它:
new Unusual().myFunction();
但是,除非您特别需要预先绑定,否则我不建议您使用这种方式定义“方法”。这在React.Component
类中很有用,但是现在有了用例的React钩子正在消失。
class Test {
constructor() { this.a = ''; }
myMethod() { console.log(this.a); }
myFunction = () => console.log(this.a);
}
const methodReference = new Test().myMethod;
try {
methodReference(); /* This will not work.
This is where an instance property can be advantageous */
} catch (ex) { console.error(ex.message); }
const functionReference = new Test().myFunction;
functionReference();