isPlainObject.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. var getPrototype = require('./_getPrototype'),
  2. isHostObject = require('./_isHostObject'),
  3. isObjectLike = require('./isObjectLike');
  4. /** `Object#toString` result references. */
  5. var objectTag = '[object Object]';
  6. /** Used for built-in method references. */
  7. var objectProto = Object.prototype;
  8. /** Used to resolve the decompiled source of functions. */
  9. var funcToString = Function.prototype.toString;
  10. /** Used to check objects for own properties. */
  11. var hasOwnProperty = objectProto.hasOwnProperty;
  12. /** Used to infer the `Object` constructor. */
  13. var objectCtorString = funcToString.call(Object);
  14. /**
  15. * Used to resolve the
  16. * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  17. * of values.
  18. */
  19. var objectToString = objectProto.toString;
  20. /**
  21. * Checks if `value` is a plain object, that is, an object created by the
  22. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  23. *
  24. * @static
  25. * @memberOf _
  26. * @since 0.8.0
  27. * @category Lang
  28. * @param {*} value The value to check.
  29. * @returns {boolean} Returns `true` if `value` is a plain object,
  30. * else `false`.
  31. * @example
  32. *
  33. * function Foo() {
  34. * this.a = 1;
  35. * }
  36. *
  37. * _.isPlainObject(new Foo);
  38. * // => false
  39. *
  40. * _.isPlainObject([1, 2, 3]);
  41. * // => false
  42. *
  43. * _.isPlainObject({ 'x': 0, 'y': 0 });
  44. * // => true
  45. *
  46. * _.isPlainObject(Object.create(null));
  47. * // => true
  48. */
  49. function isPlainObject(value) {
  50. if (!isObjectLike(value) ||
  51. objectToString.call(value) != objectTag || isHostObject(value)) {
  52. return false;
  53. }
  54. var proto = getPrototype(value);
  55. if (proto === null) {
  56. return true;
  57. }
  58. var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
  59. return (typeof Ctor == 'function' &&
  60. Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
  61. }
  62. module.exports = isPlainObject;