简体   繁体   中英

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?

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

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