Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The following function is mentioned in Speaking Javascript: An In-Depth Guide for Programmers by Axel Rauschmayer:

function getDefiningObject(obj, propKey) {
    obj = Object(obj); // make sure it’s an object
    while (obj && !{}.hasOwnProperty.call(obj, propKey)) {
        obj = Object.getPrototypeOf(obj);
        // obj is null if we have reached the end
    }
    return obj;
}

Its purpose, as the author puts it, is "to [iterate] over the property chain of an object obj [and return] the first object that has an own property with the key propKey, or null if there is no such object".

I understand the overall reasoning here, but what I don't understand is why {}.hasOwnProperty.call(obj, propKey) is being done rather than just obj.hasOwnProperty(propKey). Any ideas?

See Question&Answers more detail:os

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

1 Answer

Often, developers will use call on a built-in type to ensure that they are getting the correct native behavior of a method and not some overridden behavior.

It is a protective measure that we really shouldn't have to use, but because Objects are so malleable in JavaScript, it guarantees we get the behavior we desire.

Imagine if someone (who, intentionally or accidentally) created an object like this:

function SuperObject(){
   this.foo = function(){
     // Something here
   };

   this.hasOwnProperty = 42;
}

And then, you came along (without having seen the implementation of the object) and wrote:

var mySuperObject = new SuperObject();
console.log("Does 'mySuperObject' instance have its own 'foo' property? " +
            mySuperObject.hasOwnProperty("foo"));

You'd get this:

function SuperObject(){
  this.foo = function(){
    // Something here
  };
    
  this.hasOwnProperty = 42;
}


var mySuperObject = new SuperObject();

// Safe way:
console.log("Does 'mySuperObject' instance have its own 'foo' property? " +
             {}.hasOwnProperty.call(mySuperObject, "foo"));

// Unsafe way (fails):
console.log("Does 'mySuperObject' instance have its own 'foo' property? " +
             mySuperObject.hasOwnProperty("foo"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...