本文介绍了如何确定本机JavaScript对象是否具有属性/方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这很简单:

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" '使用此测试.

And it does work fine in Firefox, but not in IE, Chrome, Safari, Opera, they return all properties/methods of the native Array object as 'undefined' using this test.

.hasOwnProperty(prop)方法仅适用于实例...因此不起作用,但是通过反复试验,我注意到这是可行的.

The .hasOwnProperty( prop ) method only works on instances... so it doesn't work, but by trial and error I noticed that this works.

//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
}

使用此语法确定本机对象/〜"JavaScript类"〜中是否存在属性/方法是否存在问题,或者有更好的方法吗?

Is there anything wrong with using this syntax to determine if a property/method exists on a Native Object / ~"JavaScript Class"~, or is there a better way to do this?

推荐答案

首先,typeof是运算符,而不是函数,因此不需要括号.其次,访问对象的原型.

First of all, typeof is an operator, not a function, so you don't need the parentheses. Secondly, access the object's prototype.

alert( typeof Array.prototype.push );
alert( typeof Array.prototype.foo );

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

When you execute typeof Array.push you are testing if the Array object itself has a push method, not if instances of Array have a push method.

这篇关于如何确定本机JavaScript对象是否具有属性/方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:02