instanceof 和 typeof

227 阅读1分钟

简要回答

typeof

typeof一般被用于判断基本数据类型,我们可以利用 typeof 来判断number, string, object, boolean, function, undefined, symbol 这七种类型(包括symbol

typeof null  //object,null是个对象

instanceof 

判断对象的具体类型

let s = new String('abc');
typeof s === 'object' // true
s instanceof String   // true
[] instanceof Object  // true

判断一个实例是否属于某种类型

let person = function () {
}
let nicole = new person()
nicole instanceof person   // true

判断一个实例是否是其父类型或者祖先类型的实例

let person = function () {
}
let programmer = function () {
}
programmer.prototype = new person()
let nicole = new programmer()
nicole instanceof person     // true
nicole instanceof programmer // true