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

    技术2025-10-20  10

    在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                                Arrayfunction(){}                       function                            Function“a string”                          string                                String55                                      number                              Numbertrue                                   boolean                            Booleannew 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里:

    最新回复(0)