我觉得这很简单:
if(typeof(Array.push) == 'undefined'){
  //not defined, prototype a version of the push method
  // Firefox never gets here, but IE/Safari/Chrome/etc. do, even though
  // the Array object has a push method!
}
它在Firefox中运行良好,但在IE,Chrome,Safari,Opera中没有,它们使用此测试将本机Array对象的所有属性/方法返回为"undefined".
.hasOwnProperty(prop)方法仅适用于实例...所以它不起作用,但通过反复试验,我注意到这是有效的.
//this works in Firefox/IE(6,7,8)/Chrome/Safari/Opera
if(typeof(Array().push) == 'undefined'){
  //not defined, prototype a version of the push method
}
使用这种语法来确定属性/方法是否存在于Native Object /〜"JavaScript Class"上有什么问题,或者有更好的方法吗?
因为hasOwnProperty有一些警告和怪癖(窗口/广泛使用ie8问题/等).
我想知道是否有任何理由甚至使用它,如果只是测试一个属性是否未定义更合理和更简单.
例如:
var obj = { a : 'here' };
if (obj.hasOwnProperty('a')) { /* do something */ }
if (obj.a !== undefined) { /* do something */ }
// or maybe (typeof (obj.a) !== 'undefined')
只是想知道是否有人对此有任何好的见解,我更愿意使用最跨浏览器的友好和最新的方法.
我也看过这个原型覆盖了hasOwnProperty,它起作用了,但我没有卖掉它的实用性......
if (!Object.prototype.hasOwnProperty) {
    Object.prototype.hasOwnProperty = function(prop) {
        var proto = this.__proto__ || this.constructor.prototype;
        return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]);
    };
}