javascript知识点

来源:互联网 发布:萨洛蒙鞋怎么样知乎 编辑:程序博客网 时间:2024/06/05 07:58

constructor 属性

constructor 属性返回所有 JavaScript 变量的构造函数。

"good".constructor                 // 返回函数 String()  { [native code] }
(3.1415926).constructor            // 返回函数 Number()  { [native code] }
false.constructor                  // 返回函数 Boolean() { [native code] }
[1,2,3,4].constructor              // 返回函数 Array()   { [native code] }
{id:1, name:'test'}.constructor    // 返回函数 Object()  { [native code] }
new Date().constructor             // 返回函数 Date()    { [native code] }
function () {}.constructor         // 返回函数 Function(){ [native code] }


使用 constructor 属性来查看是对象是否为数组 (包含字符串 "Array"):

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}


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

function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date") > -1;
}


使用 constructor 属性来查看是对象是否为数字(包含字符串 "Number"):

function isNumber(myNumber) {
    return myNumber.constructor.toString().indexOf("Number") > -1;
}