Answer the question
In order to leave comments, you need to log in
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;
}
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
The prototype obj
can 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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question