typeof 与 intanceof 的区别(全)

1、位置不同:typeof放在变量前面,没有预判断的类型值,instanceof放在变量之后,后面跟想要判断的类型值。这个比较简单,代码如下:

var a = 0;
var b = new Array();
console.log(typeof a); // number
console.log(b instanceof Array); // true

2、判断的类型不同,typeof可以判断基本类型和引用类型,而instanceof只能判断引用类型;
3、结果不同,typeof 有
"number","boolean","string","function","object","undefined"
六种结果,且返回的值都是字符串格式,以小写开头,即

var a = 1;
console.log(typeof typeof a); // string

结果为”function”的只有函数类型:

var a = function(){}; 
console.log(typeof a); // function

结果为“object”的有三种类型,数组、对象、正则,代码如下:

var a = new Array();
var b = new Object();
var c = new RegExp();
console.log(typeof a, typeof b, typeof c); // object object object

instanceof的结果只有truefalse,它用于判断一个变量是不是某个对象的子类,它会沿着原型链__proto__向上找,如果找到匹配的对象,就返回true,否则返回false。预判断类型一般为3种:

var a = new Array();
var b = new Object();
var c = new RegExp();
var d = function(){};
var e = new d();

console.log(a instanceof Array); // true
console.log(a instanceof Object); // true

console.log(b instanceof Object); // true

console.log(c instanceof RegExp); // true
console.log(c instanceof Object); // true

console.log(d instanceof Function); // true
console.log(d instanceof Object); // true

console.log(e instanceof d); // true

最后一个行返回true是因为e是d的实例;

注意:instanceof右边必须是一个对象;

猜你喜欢

转载自blog.csdn.net/weixin_42505098/article/details/80954576