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

Categories

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

javascript - Why is hasOwnProperty being invoked generically here?

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

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

1 Answer

0 votes
by (71.8m points)

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"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...