如何通过以下逻辑访问Object.prototype方法? [英] How do I access the Object.prototype method in the following logic?
问题描述
我正在使用以下逻辑来获取给定密钥的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
, thehasOwnProperty
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 toObject.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屋!