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
822 views
in Technique[技术] by (71.8m points)

javascript - Difference between Object.prototype.hasOwnProperty.call and {}.hasOwnProperty.call.(eslint rule guard-for-in)

In the eslint rule guard-for-in , use for in directly is incorrect. The good practice is

for (key in foo) {
    if (Object.prototype.hasOwnProperty.call(foo, key)) {
        doSomething(key);
    }
    if ({}.hasOwnProperty.call(foo, key)) {
        doSomething(key);
    }
}

My question is when Object.prototype.hasOwnProperty.call(foo, key) and {}.hasOwnProperty.call(foo, key) will lead different result? Anyone can show a specific example?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

They'll never1 lead to different results, which is why both of them are considered correct.

The object {} always inherits from the object prototype and has no own keys, so accessing the .hasOwnProperty method on it will get you what you want. And Object.prototype is a non-writable property of the global Object constructor, so it always refers to the object prototype as well.

Now, there are some cases where the expression does not do what you wanted it to do:

  • Someone did overwrite the global Object variable
  • Someone did shadow the Object identifier in your scope so that it doesn't refer to the global
  • Someone did overwrite Object.prototype.hasOwnProperty with something else
  • Someone did overwrite Function.prototype.call with something else

1: Obviously, the first two edge cases only mess with the Object.prototype reference, but they're still edgy enough to be ignored.


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

...