zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    Vue购物车项目
    总结前端面试过程中最容易出现的问题
    Node.js
    浏览器前端优化
    计算机课程
    谈谈对前端的理解
    MySQL
    阿里云Centos+Django+Nginx+uWSGI
    Windows + Apache + WSGI 部署Django
    Django积木块11 —— 缓存
  • 原文地址:https://www.cnblogs.com/maxomnis/p/5740411.html
Copyright © 2011-2022 走看看