JavaScript中typeof和instanceof用法笔记

typeof一般用来获取一个变量或者表达式的类型。

     > typeof undefined
    'undefined'
    > typeof null // well-known bug
    'object'
    > typeof true
    'boolean'
    > typeof 123
    'number'
    > typeof "abc"
    'string'
    > typeof function() {}
    'function'
    > typeof {}
    'object'
    > typeof []
    'object'
    > typeof unknownVariable
    'undefined'
function SuperType(){
         }
console.log(typeof(SuperType));  //function

可以看到typeof一般返回值有undefined、Object(包括数组,NULL, 对象)、String、number、Boolean、function.

我们可以使用typeof来获取一个变量是否存在,如
if(typeof a!=”undefined”){},
而不要去使用if(a)因为如果a不存在(未声明)则会出错,

正因为typeof遇到null,数组,对象时都会返回object类型,所以当我们要判断一个对象是否是数组时

或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法instanceof.

instanceofxao操作符是一个双目运算符。判断一个对象是否是另一个对象的实例。
function SuperType(){

}
var instance = new Supertype();

alert(instance instanceof SuperType); //true;

alert(instance instanceof Object); //true ; 所有引用类型默认都是Object的实例

alert(instance instanceof Function); //false;
//instance是一个对象,而不是函数

alert(SuperType instanceof Function); //true ;

var a=new Array();alert(a instanceof Array); //true;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值