typeof,instanceof和constructor

(1)数据类型

7中基础数据类型6中原始类型以及Object类型
String,Number,Boolean,Null,Undefined,Symbol

(2)如何判断数据类型

(2.0)
typeof 判断基础数据类型 返回字符串

1
2
3
4
5
6
typeof(1) //"number"
typeof(true) //"boolean"
typeof('hello') //"string"
typeof(null) //"object"
typeof(undefined) //"undefined"
对于对象类型只能得到"object"

注意以下几处的用法:

1
2
3
4
5
6
7
8
9
typeof(null) //"object"
typeof(NaN) //"number"
typeof(typeof 1) //"string"
函数对象function setName(){} typeof(setName) //"function"
typeof Math.sin === "function";
typeof 1/0 === "NaN"
typeof alert === "function"
在 IE 6, 7 和 8 中,大多数的宿主对象是对象,而不是函数,例如:
typeof alert === "object"

(2.1)
instanceof 判断引用数据类型 返回true或者false
测试一个对象在其原型链上是否存在一个构造函数的prototype属性

1
2
var myArr = new Array();
console.log(myArr instanceof Array); //true
1
2
3
4
5
function C(){}
function D(){}
var o = new C();
// true,因为 Object.getPrototypeOf(o) === C.prototype
o instanceof C;

判断数据类型是否是数组

1
2
Array.isArray([]) //true
Object.prototype.toString.call([]) === "[object Array]" //true

(2.2)
object.constructor 返回创建实例对象的Object构造函数的引用,为只读的原始类型。

1
2
3
4
5
var son = 5;
console.log(son.constructor.name); //Number
var myArr = new Array();
console.log(myArr.constructor.name); //Array
console.log(myArr.constructor===Array); //true

示例:

1
2
3
4
5
6
7
8
9
function myFunction(name){
console.log(name)
};
var myfun = new myFunction('zsx');
console.log('myfun.constructor is '+ myfun.constructor);
//zsx
//myfun.constructor is function myFunction(name){console.log(name)}
console.log('myfun.constructor is '+ myFunction.prototype.constructor);
//myfun.constructor is function myFunction(name){console.log(name)}