typeofinstanceof和constructor

Posted 简惬

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typeofinstanceof和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;
}

 

以上是关于typeofinstanceof和constructor的主要内容,如果未能解决你的问题,请参考以下文章

python python-get-count-by-date-constructs.py

.select_on_container_copy_construction 左侧的 C++ boost::container::vector 必须具有类/结构/联合

JS基础 基本类型

JS类型检测

Java继承和构造函数

Angular 4异步加载和空时显示