Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

javascript - How do I access the Object.prototype method in the following logic?

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can access it via Object.prototype:

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

That should be safer, because

  • Not all objects inherit from Object.prototype
  • Even for objects which inherit from Object.prototype, the hasOwnProperty method could be shadowed by something else.

Of course, the code above assumes that

  • 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!

Another approach which does not need call would be

!!Object.getOwnPropertyDescriptor(obj, prop);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...