简体   繁体   English

通过调用方法创建类的实例,而无需新的关键字

[英]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). 我想通过从另一个类(Abc.CallingClass)调用函数Abc.MainClass.callMainClass()创建Abc.MainClass的新对象。 I don't want to use the new keyword there. 我不想在那里使用new关键字。

Here is the Abc.MainClass: 这是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: 这是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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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