boo*_*Yah 43 javascript ecmascript-6 eslint
我使用以下逻辑来获取给定键的i18n字符串.
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];
}
Run Code Online (Sandbox Code Playgroud)
我在我的项目中使用ESLint.我收到以下错误:
不要从目标对象访问Object.prototype方法'hasOwnProperty'.这是一个' 无原型内置 '的错误.
如何更改代码以解决此错误?我不想禁用此规则.
Ori*_*iol 72
您可以通过Object.prototype以下方式访问它
Object.prototype.hasOwnProperty.call(obj, prop);
Run Code Online (Sandbox Code Playgroud)
这应该更安全,因为
Object.prototypeObject.prototype,该hasOwnProperty方法也可能被其他东西遮蔽.当然,上面的代码假定
Object没有被遮蔽或重新定义Object.prototype.hasOwnProperty尚未重新定义call添加自己的财产Object.prototype.hasOwnPropertyFunction.prototype.call尚未重新定义如果其中任何一个不成立,尝试以更安全的方式编码,您可能会破坏您的代码!
另一种不需要的call方法是
!!Object.getOwnPropertyDescriptor(obj, prop);
Run Code Online (Sandbox Code Playgroud)
Arc*_*dze 14
@Orial 答案是正确的
用这个:
Object.prototype.hasOwnProperty.call(object, "objectProperty");
Run Code Online (Sandbox Code Playgroud)
小智 7
看来这也可以工作:
key in entries
因为这将返回一个布尔值,该键是否存在于对象内部?
对于您的特定情况,以下示例将起作用:
if(Object.prototype.hasOwnProperty.call(entries, "key")) {
//rest of the code
}
Run Code Online (Sandbox Code Playgroud)
要么
if(Object.prototype.isPrototypeOf.call(entries, key)) {
//rest of the code
}
Run Code Online (Sandbox Code Playgroud)
要么
if({}.propertyIsEnumerable.call(entries, "key")) {
//rest of the code
}
Run Code Online (Sandbox Code Playgroud)