typeof 和 instanceof 区别

typeof操作符返回一个字符串,表示未经计算的操作数的类型。

可能返回值有:"undefined"、"object"、"boolean"、"number"、"string"、"symbol"、"function"、"object"

例:

console.log(typeof 42);
// expected output: "number"

console.log(typeof 'blubber');
// expected output: "string"

console.log(typeof true);
// expected output: "boolean"

console.log(typeof declaredButUndefinedVariable);
// expected output: "undefined";

instanceof运算符用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置。

即判断一个变量是否某个对象的实例。

例:

// 定义构造函数
function C(){} 
function D(){} 

var o = new C();

o instanceof C; // true,因为 Object.getPrototypeOf(o) === C.prototype

o instanceof D; // false,因为 D.prototype不在o的原型链上

o instanceof Object; // true,因为Object.prototype.isPrototypeOf(o)返回true

猜你喜欢

转载自www.cnblogs.com/dyegral/p/10665036.html