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

猜你喜欢

转载自blog.csdn.net/superyuan567/article/details/84881164