JS类型判断&原型链

JS类型检测主要有四种

  • 1、typeof Obj
  • 2、L instanceof R
  • 3、Object.prototype.toString.call/apply();
  • 4、Obj.constructor
    Remark前两种是数据类型检查方式,后两种是构造函数判断

首先了解下显式原型prototype

  • 每一个函数(fn)在创建之后都有一个prototype, 且指向函数的原型对象, 原型对象中的constructor属性又指向fn;
    fun = function () {};
    fun.prototype// 函数包含prototype指向它的原型对象 且 fun.prototype.constructor又指向fun函数🎈🎈
    

其次了解下隐式原型__proto__

  • JS中任意一个构建的对象都有__proto__, __proto__指向创建这个对象的构造函数的prototype;
    • Array.proto => undefined;
    • Object.proto => null;
    // 1、字面量方式创建star 
      let testObj = {a: 1};
      // 实际进行了以下步骤 
      let textObj = new Object();
      textObj.a = 1;// 此时textObj有了__proto__,且__proto__指向Object.prototype
      // 同理 字面量创建一个数组
      let testArr = [];
      testArr = new Array();
    // 1、字面量方式创建end 
    // 2、通过Object.create()构造 star
      const Obj = {a: 1};
      const copyObj = Object.create(Obj);
      // 内部是这样的 
      function create(o) {
        function copy() {};
        copy.prototype = o; // **👉👉Remark此时Object.create创建的对象copyObj.__proto__直接指向Obj而不是Obj.prototype**
        return new copy(); // create也是new一个
      }
    // 2、通过Object.create()构造 end
    
    • 都是new一个实例对象

    显式原型prototype的作用

    • 用来实现基于原型的继承和属性共享

    隐式原形的作用

    • 构成原型链, 同样用于基于原型的继承, example: 当我们访问obj.a属性时, 如果obj找不到,那么会沿着__proto__依次寻找;(敲黑板: 重点是依次寻找)👈;
    • 重写__proto__
    const arr = [];
    arr.__proto__.unPush = obj => console.log(obj);
    arr.push(1); // arr本身没有push(),但是它会从隐形原型上__proto__依次查找, 找到Array.prototype上有该方法所以可以使用
    arr.unPush(2); // 2
    

typeof

  • 缺陷有两点
  • 只能判断基本数据类型除了null,不能判断引用数据类型(判断都为Object);
  • typeof 1 => 'Number';
  • typeof {} => 'Object';
  • typeof null => 'Object';
  • typeof undefined => 'undefined'

L instanceof R 判断变量是否在某一个instanceof上("实例"上)

  • 判断左边的隐式原型是否在右边的显式原型上, 不是的话依次往上找直到为null为止; (new 操作符的反向查找)
function instance_of(L, R) {
  L.__proto__ === R.prototype ? true : instance_of(L.__proto__, R);
  // 一直从隐式原型链上查找
}
  • 只能判断引用数据类型
  • 右边只能是构造函数或者对象, 不然会抛出TypeError错误

Object.prototype.toString.call/apply();最完美的检测方法, 检测所有类型

  • 实现过程????!!!📯🔔📯🔔📯🔔📯🔔

constructor

  • Obj.constructor === Number/Array/Object/Function/String/Boolean
  • 字面量或者构造函数都能检测example: new Number()
  • 不能判断null和undefined

isArray(); isNaN();

//原文链接 https://blog.csdn.net/sunshine940326/article/details/77944768

posted @ 2022-01-13 16:10  lutwelve  阅读(265)  评论(0)    收藏  举报