Skip to content

Commit

Permalink
Allow objects with no prototype to tested against object literals.
Browse files Browse the repository at this point in the history
I often use objects created with `Object.create(null)` as dictionaries, since then they don't have pre-filled dictionary entries for e.g. `constructor`, `hasOwnProperty`, `isPrototypeOf`, etc. However, in my tests, it is quite useful to test the dictionaries I create against object literals (which have `Object.prototype` as their prototype).

This patch makes an exemption to the rule that two objects must have the same constructor, for the case where one has `null` prototype and the other `Object.prototype` as its prototype.
  • Loading branch information
domenic committed Nov 1, 2011
1 parent ee15692 commit 6f9ff2f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
12 changes: 11 additions & 1 deletion qunit/qunit.js
Original file line number Diff line number Diff line change
Expand Up @@ -1065,6 +1065,10 @@ QUnit.equiv = function () {
}
}

var getProto = Object.getPrototypeOf || function (obj) {
return obj.__proto__;
};

var callbacks = function () {

// for string, boolean, number and null
Expand Down Expand Up @@ -1154,7 +1158,13 @@ QUnit.equiv = function () {
// comparing constructors is more strict than using
// instanceof
if (a.constructor !== b.constructor) {
return false;
// Allow objects with no prototype to be equivalent to
// objects with Object as their constructor.
if (!((getProto(a) === null && getProto(b) === Object.prototype) ||
(getProto(b) === null && getProto(a) === Object.prototype)))
{
return false;
}
}

// stack constructor before traversing properties
Expand Down
11 changes: 11 additions & 0 deletions test/same.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,17 @@ test("Objects Basics.", function() {
a: [{ bat: undefined }]
}
), false);

// Objects with no prototype, created via Object.create(null), are used e.g. as dictionaries.
// Being able to test equivalence against object literals is quite useful.
if (Object.create) {
equals(QUnit.equiv(Object.create(null), {}), true, "empty object with no prototype VS empty object");

var nonEmptyWithNoProto = Object.create(null);
nonEmptyWithNoProto.foo = "bar";

equals(QUnit.equiv(nonEmptyWithNoProto, { foo: "bar" }), true, "nonempty object with no prototype VS empty object");
}
});


Expand Down

0 comments on commit 6f9ff2f

Please sign in to comment.