• 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;
    }
  • 相关阅读:
    象棋中马的遍历
    字符串压缩
    寻找丑数
    Educoder
    Educoder
    以太坊:EVM的存储结构
    以太坊:EVM执行字节码的过程
    以太坊:底层序列化编码方式RLP
    以太坊:在合约里调用指定地址的另一已部署合约
    以太坊:创建合约
  • 原文地址:https://www.cnblogs.com/lixuemin/p/9004172.html
Copyright © 2020-2023  润新知