zoukankan      html  css  js  c++  java
  • typeof、instanceof和constructor

    1.js中判断是否是对象经常用到这三个关键字或者属性。下面一一介绍:

        (1)typeof运算符,通常会返回:"undefined"、"object"、"boolean"、"number" 和 "string"的字符串。数组和对象都返回"object"。数组和对象的typeof返回一致为"object"

    var o = {age: 20}; typeof o  //"object"
    var a = [1,2,3]; typeof a   //"object"
    var n = 20; typeof n   //"number"
    var b; typeof b   //"undefined"
    var f = false; typeof b   //"boolean"
    var s = 'str'; typeof s   //"string"

      (2)instanceof运算符用来判断一个构造函数的prototype属性所指向的对象是否存在另外一个要检测对象的原型链上。可以区分数组和对象

    var a = {s:2}; a instanceof Object   //true
    
    var a = [2]; a instanceof Object  //true
    var a = [2]; a instanceof Array  //true
    
    var a = 1; a instanceof Number   //false
    var a = new Number(1); a instanceof Number   //true
    
    var a = '3'; a instanceof String   //false
    var a = new String('3'); a instanceof String    //true
    
    function Person(){};
    var p =new Person();
    console.log(p instanceof Person);  //true

      (3)constructor返回对创建此对象的数组函数的引用。可以区分数组和对象

    //用法一:
    var a = {name:2}; a.constructor === Object    //true
    var a = [1,2]; a.constructor === Object    //false
    var a = 1; a.constructor === Number    //true
    var a = 'test'; a.constructor === String    //true
    var a = new Date();a.constructor === Date    //true
    
    //用法二:
    function employee(name,job,born) {
        this.name=name;
        this.job=job;
        this.born=born;
    }
    var bill=new employee("Bill Gates","Engineer",1985);
    document.write(bill.constructor);
    
    function employee(name,job,born) {
        this.name=name;
        this.job=job;
        this.born=born;
    }
  • 相关阅读:
    Vue之登录基础交互
    Vue之Slot用法初探
    序言
    sqlserver下通用 行转列 函数(原创)
    A printf format reference page (cheat sheet)
    [PowerShell]HTML parsing -- get information from a website
    [Python]打印a..z的字符
    Takari Extensions for Apache Maven (TEAM)
    【转】LAMBDAFICATOR: Crossing the gap from imperative to functional programming through refactorings
    [转][Java]使用Spring配合Junit进行单元测试的总结
  • 原文地址:https://www.cnblogs.com/lixuemin/p/9004172.html
Copyright © 2011-2022 走看看