gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:08:28 24 4
gpt4 key购买 nike

我认为下面的代码可以清楚地说明问题。

// 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 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

关于JavaScript:如何在不使用 new 关键字的情况下创建类的新实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1580863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com