[英]how to access properties across classes in JavaScript
I want to have two classes interact each other, but the class interaction is not as I expected.我想让两个类相互交互,但是类交互并不像我预期的那样。 How to fix it?
如何解决?
class InstanceActions {
static handleInstanceAction() {
console.log(this);
}
}
class main {
constructor() {
InstanceActions.handleInstanceAction(); // expected main, but undefined
}
}
new main();
Your code as written throws a syntax error, the syntax for a static method is:您编写的代码会引发语法错误,静态方法的语法是:
static methodName () {
methodBody
}
So your code should be:所以你的代码应该是:
class InstanceActions { static handleInstanceAction() { console.log(this); } } class main { constructor() { InstanceActions.handleInstanceAction(); // expected main, but undefined } } new main();
The result is:结果是:
class InstanceActions {
static handleInstanceAction() {
console.log(this);
}
}
because you're using calling handleInstanceAction as a method of InstanceActions , so it's being treated as a plain object.因为您正在使用调用handleInstanceAction作为InstanceActions的方法,所以它被视为一个普通对象。
In javascript, this is controlled by the call (except for arrow functions).在 javascript 中,这是由调用控制的(箭头函数除外)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.