instanceof和typeof

instanceof

用法  A instanceof B

官方说法是

用于测试构造函数的prototype(B)属性是否出现在对象(A)的原型链的任何位置,即constructor.prototype(A)是否存在于object(B)的原型链

function Animal(head, feet, tail){
    this.head = head
    this.feet = feet
    this.tail = tail
}

let animal = new Animal(1, 4, 1)

console.log(animal instanceof Animal) //true

没毛病,Animal的prototype出现在animal的原型链上

function Cat(name, age){
    this.name = name
    this.age = age
}

Cat.prototype = new Animal(1, 4, 1)

let cat = new Cat('Tom', 2)

console.log(cat instanceof Animal)  //true

只要B.prototype在A的原型链上的任何位置都会返回true

注意

let str1 = "Hello world"
let str2 = new String()
let str3 = new String("Hello world")

console.log(str1 instanceof String)  //false   str1并不是对象,而是一个基本类型,他没有原型链,其他基本类型同样
console.log(str2 instanceof String)  //true
console.log(str3 instanceof String)  //true

typeof

typeof用来检测数据类型,不过它只能准确地判断boolean , string , number, undefined, function ,symbol这几个类型,其他的都会返回object

console.log(typeof false);
console.log(typeof "tom");
console.log(typeof 2);
console.log(typeof undefined);
console.log(typeof function (){});
console.log(typeof Symbol());

注意:typeof 的返回值都是字符串类型,即 typeof (typeof obj) == "string"

Object.prototype.toString.call()

使用Object.prototype原生的toString()判断数据类型

我jio的这个方法是最强大的一个了

 console.log(Object.prototype.toString.call(""))                //[object String]
 console.log(Object.prototype.toString.call(1))                 //[object Number]
 console.log(Object.prototype.toString.call(true))              //[object Boolean]
 console.log(Object.prototype.toString.call(Symbol()))          //[object Symbol]
 console.log(Object.prototype.toString.call(undefined))         //[object Undefined]    
 console.log(Object.prototype.toString.call(null))              //[object Null]
 console.log(Object.prototype.toString.call({}))                //[object Object]
 console.log(Object.prototype.toString.call(function (){}))     //[object Function]
 console.log(Object.prototype.toString.call(NaN))               //[object Number] 
 console.log(Object.prototype.toString.call([]))                //[object Array]

只有number和NaN分辨不出来,NaN可以用isNaN()来判断

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值