为什么 this.hasOwnProperty('window') 在 chrome 中为真而在 IE11 中为假?

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

我运行这个代码:

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

在chrome中输出 [window]真

在 IE11 中输出 [window]假

为什么?

IE 完全搞砸了 hasOwnProperty 方法,因为它对宿主对象很痛苦(宿主对象没有 hasOwnProperty 方法)。

但是我们可以做的是直接访问 Object.prototype 以保证任何 hasOwnProperty 调用没有被篡改或覆盖。

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

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

这里的秘诀是 .call() 更改 hasOwnProperty 的上下文(接受那个,IE)并确保我们从 Object.prototype.

中获得我们想要的确切 hasOwnProperty