如何通过以下逻辑访问Object.prototype方法? [英] How do I access the Object.prototype method in the following logic?

查看:193
本文介绍了如何通过以下逻辑访问Object.prototype方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下逻辑来获取给定密钥的i18n字符串.

I am using the following logic to get the i18n string of the given key.

export function i18n(key) {
  if (entries.hasOwnProperty(key)) {
    return entries[key];
  } else if (typeof (Canadarm) !== 'undefined') {
    try {
      throw Error();
    } catch (e) {
      Canadarm.error(entries['dataBuildI18nString'] + key, e);
    }
  }
  return entries[key];
}

我在我的项目中使用ESLint.我收到以下错误:

I am using ESLint in my project. I am getting the following error:

请勿从目标对象访问Object.prototype方法'hasOwnProperty'. 这是一个' no-prototype-builtins '错误.

Do not access Object.prototype method 'hasOwnProperty' from target object. It is a 'no-prototype-builtins' error.

如何更改代码以解决此错误?我不想禁用此规则.

How do I change my code to resolve this error ? I don't want to disable this rule.

推荐答案

您可以通过Object.prototype访问它:

Object.prototype.hasOwnProperty.call(obj, prop);

那应该更安全,因为

  • 并非所有对象都继承自Object.prototype
  • 即使对于继承自Object.prototype的对象,hasOwnProperty方法也可能被其他东西遮盖.
  • Not all objects inherit from Object.prototype
  • Even for objects which inherit from Object.prototype, the hasOwnProperty method could be shadowed by something else.

当然,上面的代码假设

  • 全局Object尚未被阴影或重新定义
  • 原生Object.prototype.hasOwnProperty尚未重新定义
  • 没有call自己的财产已添加到Object.prototype.hasOwnProperty
  • 原生Function.prototype.call尚未重新定义
  • The global Object has not been shadowed or redefined
  • The native Object.prototype.hasOwnProperty has not been redefined
  • No call own property has been added to Object.prototype.hasOwnProperty
  • The native Function.prototype.call has not been redefined

如果其中任何一个都不成立,则尝试以更安全的方式进行编码,您可能已经破坏了代码!

If any of these does not hold, attempting to code in a safer way, you could have broken your code!

另一种不需要call的方法是

!!Object.getOwnPropertyDescriptor(obj, prop);

这篇关于如何通过以下逻辑访问Object.prototype方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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