Skip to content

Commit 937036f

Browse files
committed
Made isPlainObject() supporting null, undefined, and window values on IE too. Also added some related tests. Fixes jquery#5669.
1 parent 99d83fb commit 937036f

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

src/core.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -425,19 +425,21 @@ jQuery.extend({
425425
},
426426

427427
isPlainObject: function( obj ) {
428-
if ( toString.call(obj) !== "[object Object]" || typeof obj.nodeType === "number" ) {
428+
// Must be an Object.
429+
// Because of IE, we also have to check the presence of the constructor property.
430+
if ( !obj || toString.call(obj) !== "[object Object]" || !("constructor" in obj) ) {
429431
return false;
430432
}
431433

432-
// not own constructor property must be Object
434+
// Not own constructor property must be Object
433435
if ( obj.constructor
434436
&& !hasOwnProperty.call(obj, "constructor")
435437
&& !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) {
436438
return false;
437439
}
438440

439-
//own properties are iterated firstly,
440-
//so to speed up, we can test last one if it is own or not
441+
// Own properties are enumerated firstly, so to speed up,
442+
// if last one is own, then all properties are own.
441443

442444
var key;
443445
for ( key in obj ) {}

test/unit/core.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,12 +204,22 @@ test("trim", function() {
204204
});
205205

206206
test("isPlainObject", function() {
207-
expect(7);
207+
expect(14);
208208

209209
stop();
210210

211211
// The use case that we want to match
212212
ok(jQuery.isPlainObject({}), "{}");
213+
214+
// Not objects shouldn't be matched
215+
ok(!jQuery.isPlainObject(""), "string");
216+
ok(!jQuery.isPlainObject(0) && !jQuery.isPlainObject(1), "number");
217+
ok(!jQuery.isPlainObject(true) && !jQuery.isPlainObject(false), "boolean");
218+
ok(!jQuery.isPlainObject(null), "null");
219+
ok(!jQuery.isPlainObject(undefined), "undefined");
220+
221+
// Arrays shouldn't be matched
222+
ok(!jQuery.isPlainObject([]), "array");
213223

214224
// Instantiated objects shouldn't be matched
215225
ok(!jQuery.isPlainObject(new Date), "new Date");
@@ -231,6 +241,9 @@ test("isPlainObject", function() {
231241

232242
// DOM Element
233243
ok(!jQuery.isPlainObject(document.createElement("div")), "DOM Element");
244+
245+
// Window
246+
ok(!jQuery.isPlainObject(window), "window");
234247

235248
var iframe = document.createElement("iframe");
236249
document.body.appendChild(iframe);

0 commit comments

Comments
 (0)