javascript的constructor属性

本文介绍了JavaScript中的constructor属性,该属性可以返回创建特定类型对象的构造函数。通过constructor属性,可以轻松地判断一个对象是否属于特定的数据类型,如数组或日期等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
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;
}

转载于:https://www.cnblogs.com/maxomnis/p/5740411.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值