Почему isPlainObject проверка redux именно такая?

Всем привет
В Redux есть функция проверки isPlainObject , которая проверяет является ли объект переданный в dispatch() - простым
Ее реализация
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;
}

Вопрос: Почему бы вместо цикла просто не проверить так ?
function isPlainObject(obj) {
    if (typeof obj !== 'object' || obj === null) return false;

    return Object.prototype === Object.getPrototypeOf(obj);
}
  • Вопрос задан
  • 87 просмотров
Решения вопроса 1
vovaspace
@vovaspace
Frontend Engineer
Прототипом obj может быть Нечто, у которого прототип — Нечто2, у которого прототип уже Object. Цикл идёт до первого прототипа в цепочке.

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 (i.e. inheriting from null) object in the prototype chain of the argument, and then checks whether the argument directly inherits from that.

источник.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
27 апр. 2024, в 17:31
150000 руб./за проект
27 апр. 2024, в 16:39
1000 руб./в час
27 апр. 2024, в 16:38
30000 руб./за проект