constructor
constructor 属性返回所有 JavaScript 变量的构造函数。是一种用于创建和初始化 class 创建的对象的特殊方法。
"John".constructor // 返回函数 String() { [native code] }
(3.14).constructor // 返回函数 Number() { [native code] }
false.constructor // 返回函数 Boolean() { [native code] }
[1,2,3,4].constructor // 返回函数 Array() { [native code] }
{name:'John', age:34}.constructor // 返回函数 Object() { [native code] }
new Date().constructor // 返回函数 Date() { [native code] }
function () {}.constructor // 返回函数 Function(){ [native code] }
实例
使用 constructor 属性来查看对象是否为数组 (包含字符串 "Array")
var myArray = ["name","sex","age"];
function isArray(myArray) {
return mayArray.constructor.toString().indexOf("Array") > -1;
}
console.log(isArray(myArray)); //true
使用 constructor 属性来查看对象是否为日期 (包含字符串 "Date")
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
判断未知对象的类型
function isArray(obj) {
return typeof obj == 'object' && obj.constructor == Array;
}
// 测试demo
console.log(isArray([])); // true
var a = {"a":1};
console.log(isArray(a)); // false
var b = [1,2,3];
console.log(isArray(b)); // true
console.log(isArray(/\d+/g));// false