简体   繁体   中英

How to create class from inside a class in Javascript

How can we create a class from a function inside a class?

class One {
  CreateClass() {
    return class Two {
      init() {
          console.log(1234567)
      }
    }
  }
}

We look to create a class from an already created class instance like this:

var one = new Class();
var two = new one.CreateClass();
two.init();

Your One1.createClass() is not a constructor function it's return value is. So you need to invoke it and then call new on return value

 class One { CreateClass() { return class Two { init() { console.log(1234567) } } } } var One1 = new One(); var two = new (One1.CreateClass())() two.init();


I am not entirely sure how you want but you can do something like this

 function One() { this.CreateClass = class Two { init() { console.log(1234567) } } } var One1 = new One(); var two = new One1.CreateClass() two.init();

You could add new keyword after return statement so that it invokes class Two on each call of CreateClass method and returns the new instance of the class Two .

 class One { CreateClass() { return new class Two { init() { console.log(1234567) } } } } var one = new One(); var two = one.CreateClass(); two.init();

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