数据类型,判断方法,原型

109 阅读2分钟
数据类型
  1. 基本数据类型:String,Number,Boolean,Null,Undefined,Symbol
  2. 引用数据类型(对象类型):Object,Function,Array
  3. 特殊的(对象)类型:Date,RegExp
判断数据类型的方法
  1. typeof typeof在判断object,null,array的时候均会返回object.
console.log(typeof 'hello');//string
cosole.log(typeof 123)//number
cosole.log(typeof null)//object
console.log(typeof []);//object
cosole.log(typeof {})//object

  1. instanceof instanceof可以判断object,null,array,判断基本类型的时候存在问题。该方法是在判断对象和构造函数在原型链上是否有关系,如果有关系,返回真,否则返回假
console.log('hello' instanceof String);//false
cosole.log(new String("hello") instanceof String)//true

console.log([] instanceof Array)//true
console.log(object instanceof Object)//true
console.log(null instanceof Object)//false

3.constructor:通过对象实例通过constructor对象访问它的构造函数,但是可以修改,会影响判断。

function Fn(){
  console.log(123)
}
Fn.protoType = new Array()
let f = new Fn()
console.log(f.constructor() === Fn) //false
console.log(f.constructor() === Array) //true

4.Object.prototype.toString.call()

 console.log(Object.prototype.toString.call('hello'));//[object String]
 console.log(Object.prototype.toString.call(true))//[object Boolean]
 console.log(Object.prototype.toString.call(123));//[object Number]
 console.log(Object.prototype.toString.call(null));//[object Null]
 console.log(Object.prototype.toString.call(undefined));//[object Undefined]
 console.log(Object.prototype.toString.call(new Date()));//[object Date]
 console.log(Object.prototype.toString.call({}));//[object Object]
 console.log(Object.prototype.toString.call([]));//[object Array]
 console.log(Object.prototype.toString.call(/a/));//[object RegExp]
 console.log(Object.prototype.toString.call(function(){}));//[object Function]
 console.log(Object.prototype.toString.call(new Error()));//[object Error]
instanceof的实现原理

在问到判断方法之后会顺势问出这个问题,这个问题其实是在考察原型和原型链的知识。

//instanceof的函数实现
function newInstanceof(leftValue,rightValue){
  let rightProtoType = rightValue.prototype
  leftValue = leftValue.__proto__

  while(leftValue){
    // 能进入这里说明leftValue不是null,原型链没有走到头
    if(leftValue === rightProtoType){
      return true 
    }
    leftValue = leftValue.__proto__
  }

  return false
}

let ret = newInstanceof({},Object)
console.log(ret) // true

构造函数,实例,原型对象的关系

实例,构造函数,原型对象.jpg 基于上面对instanceof的了解,会往后面继续追问原型以及原型链的问题

原型和原型链

这个我不知道如何解释,可以看别人的文章辅助理解一下 原型链.png 从obj开始的原型链 obj.jpg 从函数开始的原型链,借用new String理解,不知道对不对。实际上new Object和new String都是构造函数,所以是不是不能这样看 function.jpg

  1. 上面两个手画的图其实是对第一张图的分别从obj和foo开始往后的一系列原型查找。从手画的图中可以更直观的看出,其实是进行了一模一样的操作。
  2. 两者的开始操作都是new,这个时候可能会往下询问,new操作符具体都做了什么。