The difference between typeof and instanceof in JS
Same point:
JavaScript, typeof
and instanceof
used to judge whether a variable is empty, or what type .
difference:
typeof
:
- The return value is a string , used to describe the data type of the variable .
typeof
Generally only a few returned the following results:number, boolean, string, function, object, undefined
.
if (typeof a != "undefined") {
console.log("ok");
} eles {
console.log("not ok");
}
//下面的代码是错误的
// if (a) //因为如果 a 不存在( 未声明) 则会出错。
// if (a) {
// console.log("ok");
// } else {
// console.log('cc');
// }
For special objects such as Array and Null, using typeof will always return object, which is the limitation of typeof.
instanceof
:
- The return value is
布尔值
true / false; instanceof
Used to determine whether a variable belonging to an object of实例
.
// var a = new Array();
// alert(a instanceof Array); // true
// alert(a instanceof Object) // true
//如上, Array 是 object 的子类,所以结果都为true
// alert(b instanceof Array) // b is not defined
// function Test() {
};
// var a = new test();
// alert(a instanceof test) // true
————————————————
Copyright statement: This article is the original article of the CSDN blogger "Mengli Mengyi", and it follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link for reprinting. And this statement.
Original link: https://blog.csdn.net/qq_38601916/article/details/81275091