最近在看redux的源码。但是,我无法理解 isPlainObject 中的这段代码功能:
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
export default function isPlainObject(obj) {
if (typeof obj !== 'object' || obj === null) return false
let proto = obj
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto)
}
return Object.getPrototypeOf(obj) === proto
}
我认为它像下面的代码一样工作,你能为我解释一下吗?
return Object.getPrototypeOf(obj) === Object.prototype || Object.getPrototypeOf(obj) === null
最佳答案
I think it works like the code
return Object.getPrototypeOf(obj) === Object.prototype
是的,这是基本思想。
… || Object.getPrototypeOf(obj) === null
不,这不是它检查的内容。
Could you explain?
与 Object.prototype
的相等性比较仅适用于实际继承自 Object.prototype
的对象。不过,对于普通对象而言,情况并非总是如此,它们可能来自另一个领域(如 iframe)并继承自另一个领域的 Object.prototype
。为了检测这些,代码基本上首先在参数的原型(prototype)链中搜索类Object.prototype
(即继承自null
)对象,然后检查是否参数直接继承自那个。
当然,整个循环的事情是完全没有必要的,他们可以(应该)简化为
export default function isPlainObject(obj) {
if (typeof obj !== 'object' || obj === null) return false
const proto = Object.getPrototypeOf(obj);
return proto !== null && Object.getPrototypeOf(proto) === null;
}
关于javascript - redux中isPlainObject函数的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51722354/