Last active
March 28, 2017 09:33
-
-
Save Alex1990/375966e8e2958c250905c9a2454c5977 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 hasOwn = Object.prototype.hasOwnProperty; | |
var fnToString = Function.prototype.toString; | |
var ObjectFunctionString = fnToString.call(Object); | |
// 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