Skip to content
Advertisement

How come this.hasOwnProperty(‘window’) is true in chrome and false in IE11?

I run this code:

(function () {
    console.log(this,this.hasOwnProperty('window'))
})();

In chrome it outputs [window] true

in IE11 it outputs [window] false

Why?

Advertisement

Answer

IE messes up the hasOwnProperty method completely as it’s painful with host Objects (host objects don’t have the hasOwnProperty method).

What we can do however is access the Object.prototype directly to guarantee any hasOwnProperty calls haven’t been tampered with or overridden.

var myObject= {
    prop: 'MyName',
    otherProp: null
};

if (Object.prototype.hasOwnProperty.call(myObject, 'favouriteDrink')) { // true
    // do something if it exists
}

The secret here is .call() to change the context of hasOwnProperty (take that, IE) and ensure we have the exact hasOwnProperty we want from the Object.prototype.

Advertisement