`

instanceof 运算符

 
阅读更多

typeof[(] expression [)] 这是 typeof 操作符的语法,括号是可选的The expression argument is any expression for which type information is sought寻求.

 

The typeof operator returns type information as a string. typeof操作能返回6种可能的值:"number" "string" "boolean" "object" "function" 和 "undefined."

 

 在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 "object"ECMAScript 引入了另一个 Java 运算符 instanceof 来解决这个问题。

 

instanceof 运算符与 typeof 运算符相似,用于识别正在处理的对象的类型。与 typeof 方法不同的是,instanceof 方法要求开发者明确地确认对象为某特定类型。例如:

 

var oStringObject = new String("hello world");
alert(oStringObject instanceof String);	//输出 "true"

 

这段代码问的是“变量 oStringObject 是否为 String 对象的实例?”, oStringObject 的确是 String 对象的实例,因此结果是 "true"。尽管不像 typeof 方法那样灵活,但是在 typeof 方法返回 "object" 的情况下,instanceof 方法还是很有用的。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics