如何测试两个javascript对象是否相似?

时间:2013-12-29 21:11:12

标签: javascript object

在Javascript中(请不要使用jquery或其他框架)我想测试2个(或更多)对象是否是同一类型的对象。

以下是一些示例对象:

function Person (firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
}
function Animal (name, type, age) {
    this.name = name;
    this.type = type;
    this.age = age;
}
var family = {};
family.father = new Person ('John', 'Doyle', 33);
family.mother = new Person ('Susan', 'Doyle', 32);
family.pet = new Animal ('Jodie', 'Cat', 2);

鉴于上述对象,我想要一种通用的方法来测试family.father,family.mother和family.pet是否来自同一个“类型”的对象。我可以通用的方式测试人与动物之间的区别。类似的东西:

if ( sourceObject(family.father) === sourceOjbect(family.mother) ) {
    alert('father and mother are the same type');
} else {
    alert('father and mother are not from the same object... we could have problems.');
}
if (sourceObject(family.pet) !== sourceObject(family.father)) {
    alert('the pet is a different type than the father');
} else {
    alert('Perhaps it should be a child instead of a pet?');
}

或者类似的东西:

if (isSameObject(family.pet, family.father)) {
    alert('Perhaps it should be a child instead of a pet?');
} else {
    alert('Father and pet are different.');
}

没有“sourceObject”功能,但我试图找出是否有某些功能可以做到这一点,或者有人找到了快速的方法来进行比较。

注意我不打算比较对象中的数据,我希望比较比较中涉及的对象类型。我需要在不知道所涉及的组件的确切构成的情况下这样做。例如,在上面的代码中,我可以测试“类型”属性,但这需要预先知道对象。我正在尝试编写一个泛型函数,除了对象之外,它不一定知道传递给它的对象。

5 个答案:

答案 0 :(得分:1)

您可以比较它们的构造函数

family.father.constructor == family.mother.constructor

关于构造函数的MDC

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor

的jsfiddle

http://jsfiddle.net/8LvN5/

答案 1 :(得分:0)

您可以根据原型继承比较原型。

编辑:对于浏览器兼容性,比较构造函数可能更好......

family.father.__proto__ == family.mother.__proto__ //EDIT: doesn't work in IE
//so
family.father.constructor == family.mother.constructor

所以,一般来说:

function isSameObject(obj1, obj2){ //is same prototype - actaully;
   return obj1.constructor == obj2.constructor
}

http://javascriptweblog.wordpress.com/2010/06/07/understanding-javascript-prototypes/

答案 2 :(得分:0)

使用构造函数:http://jsfiddle.net/uME8m/

alert(family.father.constructor === family.mother.constructor); //true
alert(family.father.constructor === family.pet.constructor); //false

答案 3 :(得分:0)

您可以使用.constructor.constructor.name进行比较。

family.father.constructor == family.mother.constructor
family.father.constructor == family.pet.constructor

有关对象的更多信息,请参阅here

如果你想构建一个函数,你可以这样做:

function sourceObject(obj) {
  return obj.constructor; // you can return obj.constructor.name as well
}

答案 4 :(得分:0)

您可以使用Object.getPrototypeOf()MDN Resource)获取内部[[prototype]]属性,然后只需比较这两个属性:

function isSameObject(obj1, obj2) {
    return Object.getPrototypeOf(obj1) === Object.getPrototypeOf(obj2);
}

这应该适用于所有现代浏览器,从IE9开始。

constructor属性相比的优点是,constructor属性很容易被意外覆盖,例如在实现继承时:

function A() {
}

function B() {
}

B.prototype = Object.create(A.prototype);

var b = new B();
console.log(b.constructor); //A

<强> FIDDLE