I've been doing some testing of isPlainObject functions from different libraries on different browsers.
There are 4 different (code wise) isPlainObject functions being tested on a wide range of objects:
- jquery
- lodash
- utility (a library that I'm working on)
- alternative, suggested in comments below
All four of the above show differences on Chrome v23.0.1271.95 through to Chrome v25.0.1364.160, FireFox v 19.0 an Opera v12.14, but utility at least gives the same response of false for these object on all the browsers
The tests on jsfiddle when run on Chrome
Failed to agree: JSON - jquery: true - utility: false - lodash: true - alt: false
Failed to agree: Math - jquery: true - utility: false - lodash: true - alt: false
Failed to agree: top - jquery: false - utility: false - lodash: true - alt: true
Failed to agree: parent - jquery: false - utility: false - lodash: true - alt: true
- true being that the routine thinks the object is plain, and false is not plain
EDIT: I believe that all routines are using the following similar criteria:
jquery states
Check to see if an object is a plain object (created using "{}" or "new Object").
lodash states
Checks if a given value is an object created by the Object constructor.
I understand that host objects are not the same as objects constructed by using "{}" or "new Object", so I guess my question is: should host objects be counted as plain objects?
Presently, utility is consistant and says they are not, the other routines give different results for host objects on different browsers.
EDIT: Accuracy of the result is the most important factor for me, performance is of secondary consideration.
Performance results of the 3 libraries and the suggested alternative are available on jsperf
EDIT: this is the utility library function, so you don't need to search through the code.
defineProperty(utility, "isPlainObject", {
value: (function () {
var o = {};
return function (obj) {
try {
return utility.isObject(obj) && getPrototypeOf(obj).isPrototypeOf(o);
} catch (e) {
return false;
}
};
}())
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…