redux中isPlainObject函数的实现 [英] the Implementation of isPlainObject function in redux

查看:33
本文介绍了redux中isPlainObject函数的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近在看redux的源码.但是,我无法理解 isPlainObject 功能:

Recently, I'm reading the source code of redux. But, I can't understand this code in isPlainObject function:

/**
 * @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
}

我认为它像下面的代码一样工作,你能为我解释一下吗?

I think it work like the code below ,could you explain it for me?

return Object.getPrototypeOf(obj) === Object.prototype || Object.getPrototypeOf(obj) === null

推荐答案

我认为它就像代码 return Object.getPrototypeOf(obj) === Object.prototype

是的,这是基本的想法.

Yes, that's the basic idea.

<代码>… ||Object.getPrototypeOf(obj) === null

不,这不是它检查的内容.

No, that is not what it checks for.

你能解释一下吗?

Object.prototype 的相等性比较仅适用于实际从 Object.prototype 继承的对象.然而,对于普通对象来说情况并非总是如此,它可能来自另一个领域——比如 iframe——并从另一个领域的 Object.prototype 继承.为了检测这些,代码基本上首先在参数的原型链中搜索一个类似Object.prototype(即继承自null)的对象,然后检查是否参数直接继承自那个.

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.

当然,整个循环是不必要的,他们可以(应该)简化为

Of course, the whole looping thing is quite unnecessary, they could (should) simplify to

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;
}

这篇关于redux中isPlainObject函数的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆