我一直在使用这样的构造函数模式:
function Class(parameter) {
this.id = parameter;
}
let testOne = new Class('a');
let testTwo = new Class('a');
console.log(testOne === testTwo);
console.log(testOne == testTwo);
console.log(testOne.id === testTwo.id);
如您所见,我的第一个 console.log(testOne === testTwo)
返回 false
。我认为这与以下事实有关:新构造对象的不同实例始终彼此不同,即使它具有完全相同的属性。除了直接检查其唯一和标识属性之外,还有其他方法可以检查两个对象是否具有完全相同的属性构造吗?
最佳答案
Internally js has two different approaches to check equality, for primitives (like string) it goes for value comparison and for objects(arrays ,Date object) it goes for reference(That comparison by reference basically checks to see if the objects given refer to the same location in memory.)
这是一种按值检查对象相等性的方法
function Class(parameter) {
this.id = parameter;
}
let testOne = new Class('a');
let testTwo = new Class('a');
//console.log(testOne === testTwo);//gives false
//console.log(testOne == testTwo); // gives false
//
let testThree=testOne;
console.log(testOne === testThree);//gives true (As they both refer to the same instance in memory now)
/// objects equality by value
function isEquivalent(a, b) {
// Create arrays of property names
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);
// If number of properties is different,
// objects are not equivalent
if (aProps.length != bProps.length) {
return false;
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
// If values of same property are not equal,
// objects are not equivalent
if (a[propName] !== b[propName]) {
return false;
}
}
// If we made it this far, objects
// are considered equivalent
return true;
}
// Outputs: true
console.log(isEquivalent(testOne, testTwo));
如果您觉得该方法又长又复杂,您可以尝试一些库,例如 lodash它具有用于此类任务的内置函数。
function Class(parameter) {
this.id = parameter;
}
let testOne = new Class('a');
let testTwo = new Class('a');
console.log(_.isEqual(testOne, testTwo));
// => true
console.log(testOne === testTwo);
// => false
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.js"></script>
关于javascript - 确定构造函数是否在 JavaScript 构造函数设计模式中的同一元素上调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56163841/