JavaScript:如何在不使用new关键字的情况下创建类的新实例? [英] JavaScript: How to create a new instance of a class without using the new keyword?
本文介绍了JavaScript:如何在不使用new关键字的情况下创建类的新实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为以下代码会使问题清楚。
I think the following code will make the question clear.
// 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_();
}
我不明白为什么不能使用 new
。
I don't understand why you can't use new
.
这篇关于JavaScript:如何在不使用new关键字的情况下创建类的新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文