Created
March 28, 2017 09:22
-
-
Save Alex1990/61aa25cbb09f32660731d29cdde8ee39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Tests: | |
* - `isPlainObject(null)` | |
* - `isPlainObject([1, 2, 3])` | |
* - `isPlainObject(window)` | |
* - `isPlainObject(new String('hello'))` | |
* - `isPlainObject(Object.create(null))` | |
* - `isPlainObject({ a: 1, b: 2 })` | |
* - `isPlainObject(new Person('Alex'))` | |
* | |
* `Person`: | |
* ``` | |
* function Person(name) { | |
* this.name = name; | |
* } | |
* Person.prototype = { | |
* getName: function () { | |
* return this.name; | |
* } | |
* }; | |
* ``` | |
* | |
* Ref: | |
* - jQuery 3.x isPlainObject | |
*/ | |
var toString = Object.prototype.toString; | |
var fnToString = Function.prototype.toString; | |
var ObjectFunctionString = fnToString.call(Object); | |
function hasOwn (obj, prop) { | |
return Object.prototype.hasOwnProperty.call(obj, prop); | |
} | |
// Object.getPrototypeOf polyfill: core-js or es5-shim | |
function getProto(obj) { | |
return Object.getPrototypeOf(obj); | |
} | |
function isPlainObject (obj) { | |
if (obj === null || toString.call(obj) !== '[object Object]') { | |
return false; | |
} | |
var proto = getProto(obj); | |
if (!proto) { | |
return true; | |
} | |
var Ctor = hasOwn.call(proto, 'constructor') && proto.constructor; | |
return typeof Ctor === 'function' && fnToString.call(Ctor) === ObjectFunctionString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment