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

scu*_*ffe 21 javascript methods native properties typeof

我觉得这很简单:

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"上有什么问题,或者有更好的方法吗?

小智 56

检查属性是否存在的正确方法:

if ('property' in objectVar)
Run Code Online (Sandbox Code Playgroud)


Pet*_*ley 32

首先,typeof是一个操作符,而不是一个函数,所以你不需要括号.其次,访问对象的原型.

alert( typeof Array.prototype.push );
alert( typeof Array.prototype.foo );
Run Code Online (Sandbox Code Playgroud)

执行时,typeof Array.push您正在测试Array对象本身是否具有push方法,而不是Array的实例是否具有push方法.

  • 这不适用于所有情况.例如(typeof XMLHttpRequest.prototype.onload!=='undefined')抛出TypeError:非法调用.正确的方法是:( XMLHttpRequest.prototype中的'onload') (2认同)

小智 8

.hasOwnProperty可以在阵列的proptotype访问,如果typeof不地道不够.


if (Array.prototype.hasOwnProperty('push')) {
    // Native array has push property
}