您的位置:首页 > Web前端 > JQuery

jquery源码阅读知识储备(6)typeof 和 instanceof的结合使用

2011-02-15 23:10 447 查看
在java里判断一个对象是否是另外一个对象的实例,可以用instanceof或instanceof在对象类型的强制转换,先判断是否是某种类型,是的话再强制转换成改类型。

var obj = new Object();
var array = new Array(1,2,3,4);
alert(typeof(obj));//object
alert(typeof(array));//object

alert(obj instanceof Array);//false
alert(array instanceof Array);//true


typeof用以获取一个变量的类型,typeof一般只能返回如下几个结果:number,boolean,string,function,object,undefined对于Array,Null等特殊对象使用typeof 一律返回object,这正是typeof的局限性。

Variable typeof Variable Variable.constructor
{ an: “object” } object Object
[ “an”, “array” ] object Array
function(){} function Function
“a string” string String
55 number Number
true boolean Boolean
new User() object User

if ( num.constructor == String )
// If it is, then parse a number out of it
num = parseInt( num );
// Check to see if our string is actually an array
if ( str.constructor == Array )
// If that's the case, make a string by joining the array using commas
str = str.join(',');


如果我们希望获取一个对象是否是数组,或判断某个变量是否是某个对象的实例则要选择使用instanceof。



var a=new Array();

alert(a instanceof Array);//会返回true

// 同时alert(a instanceof Object)也会返回true;这是因为Array是object的子类。


再如:

function test(){};

var a=new test();

alert(a instanceof test)//会返回true。


而在js里:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: