typeof 和 instanceof

var numValue = 1.9,
boolValue = true,
strValue = "asdfasdf" + "ds",
dateValue = new Date(),
arrValue = [1, 2],
funcValue = function() {},
objValue = new Object(),
nullValue = null,

objValue1 = {};

var types = typeof numValue + "\n" + // number
typeof boolValue + "\n" + // boolean
typeof strValue + "\n" +   // string
typeof dateValue + "\n" + // object
typeof arrValue + "\n" +   // object
typeof funcValue + "\n" + // function
typeof objValue + "\n" +  // pbject
typeof nullValue + "\n" +   // object

typeof objValue1;             // object

alert(strValue instanceof String); // false
alert(numValue instanceof Number); // false
alert(arrValue instanceof Array); // true
alert(dateValue instanceof Date); // true
alert(funcValue instanceof Function); // true

alert(objValue1 instanceof Object);    // true
alert(typeof String); // function
alert(typeof Number); // function
alert(typeof Array); // function
alert(typeof Date); // function
alert(typeof Function); // function

这里仅仅是做一个记录。比较有意思的是:

alert(strValue instanceof String); // false
alert(numValue instanceof Number); // false 

这两个与我原来的理解不一样。那么当此类变量在使用String or Number类型的函数时,就会有隐式类型转换。

这也是JS性能优化的一个方面。那就是尽量少用隐式类型转换。

posted @ 2014-04-05 23:53  临风远望  阅读(173)  评论(0编辑  收藏  举报