javascript的constructor属性

/*
constructor 属性
constructor 属性返回所有 JavaScript 变量的构造函数。
*/
console.log("John".constructor); // 返回函数 String() { [native code] }
console.log((3.14).constructor); // 返回函数 Number() { [native code] }
console.log(false.constructor); // 返回函数 Boolean() { [native code] }
console.log([1,2,3,4].constructor); // 返回函数 Array() { [native code] }
console.log({name:'John', age:34}.constructor); // 返回函数 Object() { [native code] }
console.log(new Date().constructor); // 返回函数 Date() { [native code] }
console.log(function () {}.constructor); // 返回函数 Function(){ [native code] }

/*
因为typeof Date, 和typeof Array返回的都是object,所以分辨不出来到底是Date还是Array,可以使用constructor判断
*/

/*
你可以使用 constructor 属性来查看是对象是否为数组 (包含字符串 "Array"):
*/
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}

/*
你可以使用 constructor 属性来查看是对象是否为日期 (包含字符串 "Date"):
*/

function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
posted @ 2016-08-05 10:50  maxomnis  阅读(294)  评论(0编辑  收藏  举报