V
V
Viktor Dubrov2020-12-12 19:15:18
React
Viktor Dubrov, 2020-12-12 19:15:18

Why is redux check isPlainObject like this?

Hello everyone
Redux has a check function isPlainObject that checks if the object passed to dispatch() is a simple one
. Its implementation

function isPlainObject(obj) {
  if (typeof obj !== 'object' || obj === null) return false;
  var proto = obj;

  while (Object.getPrototypeOf(proto) !== null) {
    proto = Object.getPrototypeOf(proto);
  }

  return Object.getPrototypeOf(obj) === proto;
}

Question: Why not just check like this instead of a loop?
function isPlainObject(obj) {
    if (typeof obj !== 'object' || obj === null) return false;

    return Object.prototype === Object.getPrototypeOf(obj);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Lewandowski, 2020-12-12
@victor1985

The prototype objcan be Нечто, whose prototype is Нечто2, whose prototype is already Object. The loop goes up to the first prototype in the chain.
UPD:


A comparison for equality with Object.prototype only works for objects that actually inherit from Object.prototype. This is not always the case for plain objects though, which might come from another realm - like an iframe - and inherit from the other realm's Object.prototype. To detect these, the code basically first searches for an Object.prototype-like (ie inheriting from null) object in the prototype chain of the argument, and then checks whether the argument directly inherits from that.

- source .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question