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

ave*_*net 22 javascript oop constructor instance

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

// 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);
Run Code Online (Sandbox Code Playgroud)

Cor*_*tin 27

一种更简单,更清洁的方式,没有"工厂"

function Person(name) {
  if (!(this instanceof Person)) return new Person(name);
  this.name = name;
}

var p1 = new Person('Fred');
var p2 = Person('Barney');

p1 instanceof Person  //=> true
p2 instanceof Person  //=> true
Run Code Online (Sandbox Code Playgroud)


dav*_*420 19

这不行吗?

function factory(class_) {
    return new class_();
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么你不能使用new.

  • 规定没有使用"新" (2认同)
  • 好的热门镜头,你如何将参数列表应用于这个新创建的类?;)新类_().apply(this,array)我不这么认为 (2认同)

Mat*_*ley 7

如果您真的不想使用该new关键字,并且您不介意只支持Firefox,则可以自行设置原型.然而,这并没有任何意义,因为你可以使用Dave Hinton的答案.

// This is essentially what the new keyword does
function factory(clazz) {
    var obj = {};
    obj.__proto__ = clazz.prototype;
    var result = clazz.call(obj);
    return (typeof result !== 'undefined') ? result : obj;
};
Run Code Online (Sandbox Code Playgroud)