相关疑难解决方法(0)

如何确定Native JavaScript Object是否具有属性/方法?

我觉得这很简单:

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!
}
Run Code Online (Sandbox Code Playgroud)

它在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
}
Run Code Online (Sandbox Code Playgroud)

使用这种语法来确定属性/方法是否存在于Native Object /〜"JavaScript Class"上有什么问题,或者有更好的方法吗?

javascript methods native properties typeof

21
推荐指数
3
解决办法
5万
查看次数

如果未定义Property,则使用Object.hasOwnProperty与测试的好处

因为hasOwnProperty有一些警告和怪癖(窗口/广泛使用ie8问题/等).

我想知道是否有任何理由甚至使用它,如果只是测试一个属性是否未定义更合理和更简单.

例如:

var obj = { a : 'here' };

if (obj.hasOwnProperty('a')) { /* do something */ }

if (obj.a !== undefined) { /* do something */ }
// or maybe (typeof (obj.a) !== 'undefined')
Run Code Online (Sandbox Code Playgroud)

只是想知道是否有人对此有任何好的见解,我更愿意使用最跨浏览器的友好和最新的方法.

我也看过这个原型覆盖了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]);
    };
}
Run Code Online (Sandbox Code Playgroud)

javascript jquery object undefined hasownproperty

13
推荐指数
3
解决办法
2万
查看次数