简体   繁体   中英

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.

In javascript, this is controlled by the call (except for arrow functions).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM