JS基础之typeof和instanceof用法

typeof

在js中当不确定操作数的类型时,可以通过typeof()函数返回变量的类型。
typeof()函数会把类型信息当做字符串返回,且typeof的返回值有六种情况,这六种返回值类型分别是:

  • number
  • string
  • boolean
  • undefined
  • object
  • function
    注意:返回值类型都是字符串类型

typeof的使用:

  • typeof(value): 可以通过小括号传值的方式来获取操作数类型
  • typeof value: 也可以不加小括号获取操作数类型

举例说明:

        console.log(typeof(null));  //object
        console.log(typeof(a));   //undefined
        console.log(typeof(123));  //number
        console.log(typeof("123"));  //string
        console.log(typeof(true));  //boolean
        console.log(typeof(typeof(null)));    //string
        console.log(typeof([123]));    //object
        console.log(typeof({}));        //object

instanceof

instanceof 可以用于测试是否为引用类型(Object, Array, Function, Date, RegExp, 包装类(Number, String, Boolean))。
由于typeof只能判断类型,所以,数组和对象返回的都是object,这时就需要使用instanceof来判断是数组还是对象。

  1. 判断对象是否是指定的构造函数的实例。
  2. 还可以判断原型链上是否有指定的原型。
Father.prototype.lastName = "wang";
function Father(){
}
var father = new Father()
Son.prototype = father;
function Son(name,age){
	this.name = name;
	this.age = age;
}
var person1 = new Son("aaa",18);
console.log(person1 instanceof Son);         //true
console.log(person1 instanceof Father);     //true
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值