I'm trying to write a node.js script and want to keep the dependencies on the minimum. I want to make sure that a given argument called config
is a plain object, like this:
var config = {
'key1': 'val1',
'key2': 'val2',
'key3': 'val3'
/* ... */
}
Now the first thing that came to mind was something like this:
if (Object.prototype.toString.call(config) !== '[object Object]') {
/* ... */
}
Can anyone think of an example where this wouldn't hold? I thought it was better to add:
if (typeof config !== 'object' ||
Object.prototype.toString.call(config) !== '[object Object]') {
/* ... */
}
just to be sure! But I'm still not convinced it could be this easy. I need
Thank you very much for your time folks.
I had a look at jQuery source, and particularly at the function jQuery.isPlainObject()
and it uses a slightly more complex approach. Where I am looking to establish if it's a plain object, jQuery is making sure it's not anything other than a plain object. Have a look here:
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.constructor &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
}