Search code examples
javascriptnew-operator

Create instance of class by calling method, without new keyword


I want to create a new object of Abc.MainClass by calling function Abc.MainClass.callMainClass() from another class (Abc.CallingClass). I don't want to use the new keyword there.

Here is the Abc.MainClass:

goog.provide('Abc.MainClass');

Abc.MainClass.callMainClass = function() {
    var config = null;
    return new Abc.MainClass(config);
}

Abc.MainClass= function(config) {
}

Here is the Abc.CallingClass:

goog.require('Abc.MainClass');

this.mainClass = Abc.MainClass.callMainClass;
this.mainClass();

Of course it doesn't work. Do you know why it is wrong? How should I implement such thing?


Solution

  • Actually sequence of your implementation is incorrect. Update it as below.

    Abc.MainClass = function(config) {
    
    }
    
    Abc.MainClass.callMainClass = function() {
        var config = null;
        return new Abc.MainClass(config);
    }