javascript - 确定构造函数是否在 JavaScript 构造函数设计模式中的同一元素上调用

标签 javascript constructor

我一直在使用这样的构造函数模式:

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/

相关文章:

javascript - 创建重复值的JS数组

javascript - 在 javascript 中为所有浏览器设置 innerHTML

javascript - 从 JavaScript 中的字符串中删除圆括号 - ( 和 )

javascript - 单击按钮即可触发 2 个操作

c++ - 作为类成员的 `std::array<int, N>`中的元素是否默认初始化

c++ - SFINAE 条件和构造函数参数类型

javascript - jquery .delegate 和动态内容

c++ - 如何仅在复制构造函数存在时调用它?由 小码哥发布于

c++ - 是 *this = Ctor();清除对象状态合法有效?

Java UNIXProcess 在 Eclipse 中不可见?