简体   繁体   English

如何在JavaScript中创建构造函数,以便如果使用'new'关键字创建的两个实例,instance1 === instance2的值返回true

[英]How to create a constructor function in javascript so that if two instance created with 'new' keyword the value of instance1 === instance2 return true

I was finding a way, if I can make this code work. 如果可以使此代码正常工作,我正在寻找一种方法。 I cannot use prototype and I want to create the instance using "new" keyword only. 我不能使用原型,我只想使用“ new”关键字创建实例。

function Employee(name) {
    this.name = name;
}
var e1 = new Employee();
var e2 = new Employee();
e1 === e2; // Expected result should be true.

new sets the contructor property of the object. new设置对象的contructor属性。 If you want to check if they were created by the same constructor, you could compare those: 如果要检查它们是否由相同的构造函数创建,则可以比较它们:

 function Employee(name) { this.name = name; } var e1 = new Employee('foo'); var e2 = new Employee('bar'); var x = new Date(); console.log(e1.constructor === e2.constructor); // true console.log(e1.constructor === x.constructor); // false 

If you want to use the new keyword and you want the result to be a singleton, then you can do something like this: 如果要使用new关键字,并且希望结果为单例,则可以执行以下操作:

 var Employee = (function () { var instance; return function Employee(name) { if (!instance) { this.name = name; instance = this; } return instance; } })(); var a = new Employee('a'); var b = new Employee('b'); // They pass the === check console.log('===', a === b); // But they have the same name because they're the same object console.log('a.name', a.name); console.log('b.name', b.name); // And changing one changes them both because, again, they're the same object a.name = 'z'; console.log('a.name', a.name); console.log('b.name', b.name); 

Normally when you call a constructor, new creates a new object, which you can add to by accessing this , and then that newly created object is returned. 通常,当您调用构造函数时, new创建一个新对象,您可以通过访问this将其添加到this对象中,然后返回该新创建的对象。 However, if you explicitly return something from your constructor, then that object will be used instead of the one that new would normally create. 但是,如果您从构造函数中显式返回某些内容,则将使用该对象,而不是new通常创建的对象。 So i've set up the code so that the constructor always returns the same instance, which i've then trapped inside an IIFE to make it "private". 因此,我设置了代码,以便构造函数始终返回相同的实例,然后将其困在IIFE中以使其变为“私有”。

But notice that since a and b are literally the same object, they both have the same name. 但是请注意,由于a和b实际上是相同的对象,因此它们都具有相同的名称。 In my case, the first name sticks and the second one is ignored. 在我的情况下,第一个名字会保留,第二个名字会被忽略。 You could modify the code to make the second name overwrite the first one, but it's impossible for them to have different names while still meeting your requirements that a === b. 您可以修改代码以使第二个名称覆盖第一个名称,但是在满足a === b要求的同时,它们不可能具有不同的名称。

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

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