本文主要是介绍JS基础之typeof和instanceof用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
typeof
在js中当不确定操作数的类型时,可以通过typeof()函数返回变量的类型。
typeof()函数会把类型信息当做字符串返回,且typeof的返回值有六种情况,这六种返回值类型分别是:
- number
- string
- boolean
- undefined
- object
- function
注意:返回值类型都是字符串类型
typeof的使用:
- typeof(value): 可以通过小括号传值的方式来获取操作数类型
- typeof value: 也可以不加小括号获取操作数类型
举例说明:
console.log(typeof(null)); //objectconsole.log(typeof(a)); //undefinedconsole.log(typeof(123)); //numberconsole.log(typeof("123")); //stringconsole.log(typeof(true)); //booleanconsole.log(typeof(typeof(null))); //stringconsole.log(typeof([123])); //objectconsole.log(typeof({})); //object
instanceof
instanceof 可以用于测试是否为引用类型(Object, Array, Function, Date, RegExp, 包装类(Number, String, Boolean))。
由于typeof只能判断类型,所以,数组和对象返回的都是object,这时就需要使用instanceof来判断是数组还是对象。
- 判断对象是否是指定的构造函数的实例。
- 还可以判断原型链上是否有指定的原型。
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
这篇关于JS基础之typeof和instanceof用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!