国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > web前端 > jscript > 详解js中typeof、instanceof与constructor

详解js中typeof、instanceof与constructor

来源:程序员人生   发布时间:2013-11-26 04:27:03 阅读次数:2687次

  typeof返回一个表达式的数据类型的字符串,返回结果为js基本的数据类型,包括number,boolean,string,object,undefined,function.语法为typeof(data) 或 typeof data

  instanceof则为判断一个对象是否为某一数据类型,或一个变量是否为一个对象的实例;返回boolean类型

  语法为 o instanceof A

  以下为综合实例:

以下为引用的内容:
<script type="text/javascript">
<!–
alert("typeof(1):" + typeof(1));//number
alert("typeof("abc"):" + typeof("abc"));//string
alert("typeof(true):" +typeof(true));//boolean
alert("typeof(2009-2-4):" + typeof(2009-2-4));//number
alert("typeof("2009-2-4"):" + typeof("2009-2-4"));//string
alert("typeof(m):" + typeof(m));//undefined
var d=new Date();
alert("typeof(d):" + typeof(d));//object
function Person(){};
alert("typeof(Person):" + typeof(Person));//function
var a=new Array();
alert("typeof(a):" + typeof(a));//object
alert("a instanceof Array:" + (a instanceof Array));
var h=new Person();
var o={};
alert("h instanceof Person:" + (h instanceof Person));//true
alert("h instanceof Object:" + (h instanceof Object));//true
alert("o instanceof Object:" + (o instanceof Object));//true
alert(typeof(h));//object
//–>
</script>

  js中constructor较少使用,如果不是搜索到相关construtor相关的资料,我之前从没有注意到js还有这个函数。使用typeof的一个不好的地方就是它会把Array还有用户自定义函数都返回为object。

以下为引用的内容:
<script type="text/javascript">
<!–
var j=2;
alert(typeof(j));//number
alert("j.constructor:" + j.constructor);//function …
alert(typeof(j.constructor));//function
//–>
</script>

  可以看到js.constructor返回的是一些字符串,大家都应该能看到这是一个function类型,此例为Number()为Number对象的构造函数,Number()用于将其参数转换为数字number类型,并返回转换结果(若不能转换则返回 NaN)。

  因此在以后的js判断数据类型时可以使用以下方式来得到其详细数据类型。

以下为引用的内容:
if((typeof o=="object") && (o.constructor==Number)){

}

  这里还要注意,constructor只能对已有变量进行判断,而typeof则可对未声明变量进行判断(返回undefined)。

  转自:http://www.51obj.cn/

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生