typeof 和 instanceof 区别

2022-10-22,,

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

 

《typeof 和 instanceof 区别.doc》

下载本文的Word格式文档,以方便收藏与打印。