当前位置: 移动技术网 > IT编程>开发语言>JavaScript > typeof 和 instanceof 区别

typeof 和 instanceof 区别

2019年04月08日  | 移动技术网IT编程  | 我要评论

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

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网