繁体   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

如果可以使此代码正常工作,我正在寻找一种方法。 我不能使用原型,我只想使用“ new”关键字创建实例。

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

new设置对象的contructor属性。 如果要检查它们是否由相同的构造函数创建,则可以比较它们:

 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 

如果要使用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); 

通常,当您调用构造函数时, new创建一个新对象,您可以通过访问this将其添加到this对象中,然后返回该新创建的对象。 但是,如果您从构造函数中显式返回某些内容,则将使用该对象,而不是new通常创建的对象。 因此,我设置了代码,以便构造函数始终返回相同的实例,然后将其困在IIFE中以使其变为“私有”。

但是请注意,由于a和b实际上是相同的对象,因此它们都具有相同的名称。 在我的情况下,第一个名字会保留,第二个名字会被忽略。 您可以修改代码以使第二个名称覆盖第一个名称,但是在满足a === b要求的同时,它们不可能具有不同的名称。

暂无
暂无

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

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