0

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();
11
  • (Use objects instead?) Do you want to return a new instance, or a class object? Commented Apr 1, 2020 at 16:27
  • We want to return a new instance. Commented Apr 1, 2020 at 16:29
  • 1
    Move Two outside One, and return new Two in CreateClass? Commented Apr 1, 2020 at 16:31
  • 1
    Can you just do this jsfiddle.net/y1whgx5q ? Commented Apr 1, 2020 at 16:43
  • 1
    @NenadVracar off site links are not useful to other users of this site. Especially when those links become broken. Commented Apr 1, 2020 at 16:46

2 Answers 2

2

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();

Sign up to request clarification or add additional context in comments.

4 Comments

Is there any way to just do like One1.CreateClass() something similar to this: web3js.readthedocs.io/en/v1.2.4/web3.html#id12
@SowmayJain look at the second snippet, is this what you want to achieve ?
The prior version suits best. Is there any way to access the functions in Class One inside the new instance of Class Two? this.functionName doesn't work as this not relates to Class Two.
@SowmayJain you can extend class two from class one, class Two extends One
1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.