isPlainObject.js 1.6 KB

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