• JavaScript类型检测, typeof操作符与constructor属性的异同


    *#type.js

    function Person(name, age) {
    	this.name = name;
    	this.age = age;
    }
    
    var d = {an: 'object'};
    var a = ['apple', 'banana'];
    var f = function() {};
    var s = 'David';
    var n = 33;
    var b = true;
    var o = new Object();
    var person = new Person('Mark', 22);
    
    console.log(typeof(d) + ': ' + d.constructor);
    console.log(typeof(a) + ': ' + a.constructor);
    console.log(typeof(f) + ': ' + f.constructor);
    console.log(typeof(s) + ': ' + s.constructor);
    console.log(typeof(n) + ': ' + n.constructor);
    console.log(typeof(b) + ': ' + b.constructor);
    console.log(typeof(o) + ': ' + o.constructor);
    console.log(typeof(person) + ': ' + person.constructor);
    
    

    运行$node type.js

    object:   function Object() { [native code] }
    object:   function Array() { [native code] }
    function: function Function() { [native code] }
    string:   function String() { [native code] }
    number:   function Number() { [native code] }
    boolean:  function Boolean() { [native code] }
    object:   function Object() { [native code] }
    object:   function Person() { [native code] }
    
    

    可见, 使用typeof操作符和constucor属性检测对象类型返回值是存在差异的.

    1. 如果变量是数组, typeof操作符返回object, constructor属性返回Array;
    2. 如果变量是构造函数对象, typeof操作符返回object, constructor属性返回该构造函数

    每个变量都有其construcor属性, 这个属性不单单提供了这个是否对象, 还提供了这个对象是什么类型的对象. 总之, constructor属性保存了一个指向对象的构造函数, 无论它是自定义的还是原生类型的对象.

    有一点需要注意的是, 不同的浏览器对typeof操作符检测正则表达式会有所不同,IE和Firefox会返回'object'.

  • 相关阅读:
    测试:安装测试用例
    测试:界面测试
    软件项目管理:什么是baseline
    测试:fiddler使用
    android adb常用指令
    sqlite语句主页
    几条常见的数据库分页 SQL 语句
    linux下tomcat无法访问问题(换一种说法:无法访问8080端口)
    eclipse中svn的各种状态图标详解
    Tomcat项目部署方式
  • 原文地址:https://www.cnblogs.com/lozio/p/4299786.html
Copyright © 2020-2023  润新知