Made isPlainObject() supporting null, undefined, and window values on IE too. Also added some related tests. Fixes #5669.

This commit is contained in:
Robert Katic 2009-12-19 00:34:20 +08:00 committed by John Resig
parent 27d65b59f9
commit 148fb7ba8e
2 changed files with 20 additions and 5 deletions

View file

@ -425,19 +425,21 @@ jQuery.extend({
},
isPlainObject: function( obj ) {
if ( toString.call(obj) !== "[object Object]" || typeof obj.nodeType === "number" ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
if ( !obj || toString.call(obj) !== "[object Object]" || !("constructor" in obj) ) {
return false;
}
// not own constructor property must be Object
// Not own constructor property must be Object
if ( obj.constructor
&& !hasOwnProperty.call(obj, "constructor")
&& !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
//own properties are iterated firstly,
//so to speed up, we can test last one if it is own or not
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}

View file

@ -204,12 +204,22 @@ test("trim", function() {
});
test("isPlainObject", function() {
expect(7);
expect(14);
stop();
// The use case that we want to match
ok(jQuery.isPlainObject({}), "{}");
// Not objects shouldn't be matched
ok(!jQuery.isPlainObject(""), "string");
ok(!jQuery.isPlainObject(0) && !jQuery.isPlainObject(1), "number");
ok(!jQuery.isPlainObject(true) && !jQuery.isPlainObject(false), "boolean");
ok(!jQuery.isPlainObject(null), "null");
ok(!jQuery.isPlainObject(undefined), "undefined");
// Arrays shouldn't be matched
ok(!jQuery.isPlainObject([]), "array");
// Instantiated objects shouldn't be matched
ok(!jQuery.isPlainObject(new Date), "new Date");
@ -231,6 +241,9 @@ test("isPlainObject", function() {
// DOM Element
ok(!jQuery.isPlainObject(document.createElement("div")), "DOM Element");
// Window
ok(!jQuery.isPlainObject(window), "window");
var iframe = document.createElement("iframe");
document.body.appendChild(iframe);