JavaScript:如何在不使用新关键字的情况下创建类的新实例?

我认为以下代码将使问题清楚。

// My class
var Class = function() { console.log("Constructor"); };
Class.prototype = { method: function() { console.log("Method");} }

// Creating an instance with new
var object1 = new Class();
object1.method();
console.log("New returned", object1);

// How to write a factory which can't use the new keyword?
function factory(clazz) {
    // Assume this function can't see "Class", but only sees its parameter "clazz".
    return clazz.call(); // Calls the constructor, but no new object is created
    return clazz.new();  // Doesn't work because there is new() method
};

var object2 = factory(Class);
object2.method();
console.log("Factory returned", object2);
最佳答案
这不工作吗?

function factory(class_) {
    return new class_();
}

我不明白为什么你不能使用新的。

转载注明原文:JavaScript:如何在不使用新关键字的情况下创建类的新实例? - 代码日志