isPlainObject.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var baseForIn = require('../internal/baseForIn'),
  2. isArguments = require('./isArguments'),
  3. isObjectLike = require('../internal/isObjectLike');
  4. /** `Object#toString` result references. */
  5. var objectTag = '[object Object]';
  6. /** Used for native method references. */
  7. var objectProto = Object.prototype;
  8. /** Used to check objects for own properties. */
  9. var hasOwnProperty = objectProto.hasOwnProperty;
  10. /**
  11. * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
  12. * of values.
  13. */
  14. var objToString = objectProto.toString;
  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. * **Note:** This method assumes objects created by the `Object` constructor
  20. * have no inherited enumerable properties.
  21. *
  22. * @static
  23. * @memberOf _
  24. * @category Lang
  25. * @param {*} value The value to check.
  26. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  27. * @example
  28. *
  29. * function Foo() {
  30. * this.a = 1;
  31. * }
  32. *
  33. * _.isPlainObject(new Foo);
  34. * // => false
  35. *
  36. * _.isPlainObject([1, 2, 3]);
  37. * // => false
  38. *
  39. * _.isPlainObject({ 'x': 0, 'y': 0 });
  40. * // => true
  41. *
  42. * _.isPlainObject(Object.create(null));
  43. * // => true
  44. */
  45. function isPlainObject(value) {
  46. var Ctor;
  47. // Exit early for non `Object` objects.
  48. if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) ||
  49. (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
  50. return false;
  51. }
  52. // IE < 9 iterates inherited properties before own properties. If the first
  53. // iterated property is an object's own property then there are no inherited
  54. // enumerable properties.
  55. var result;
  56. // In most environments an object's own properties are iterated before
  57. // its inherited properties. If the last iterated property is an object's
  58. // own property then there are no inherited enumerable properties.
  59. baseForIn(value, function(subValue, key) {
  60. result = key;
  61. });
  62. return result === undefined || hasOwnProperty.call(value, result);
  63. }
  64. module.exports = isPlainObject;