You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionmyInstanceof(inst,ctor){// 是否为函数对象constisCallable=val=>typeofval==='function'// 是否为引用值constisObject=val=>typeofval==='function'||(val!==null&&typeofval==='object')// ctor 必须是引用值if(!isObject(ctor))thrownewTypeError(`Right-hand side of 'instanceof' is not an object`)// ctor 必须是函数对象if(!isCallable(ctor))thrownewTypeError(`Right-hand side of 'instanceof' is not callable`)// inst 为原始值,则返回 falseif(!isObject(inst))returnfalsedo{constproto=inst.__proto__// 可换成标准方法 const proto = Object.getPrototypeOf(inst)// 原型链顶端(proto 为 null)或者 inst 通过 Object.create(null) 构造(proto 为 undefined)if(proto==null)returnfalseif(proto===ctor.prototype)returntrueinst=proto// 往上一级查找}while(true)}
The end.
The text was updated successfully, but these errors were encountered:
开始之前,先了解一些基本背景...
一、前言
我们知道,在 ECMAScript 标准中,当前数据类型分为两类(共 8 种):
其中,原始值都是不可改变的,且不含任何属性或方法。平时看到类似的
'string'.length
写法,本质上是发生了隐式类型转换,先将'string'
转换为Object('string')
,然后调用String
实例对象的length
属性罢了。下面,我们将「引用类型」划分为两类:
注意,这里提到的对象泛指引用类型,而不是单指平常所写的
{...}
对象。请记住:前面划分对象,就是为了方便分清楚
prototype
(原型对象)和__proto__
(原型)的区别:换句话说:
不作过多介绍,如果对这俩兄弟不太了解的,可看文章数据类型详解。
二、instanceof
从 MDN 可知,其语法非常简单:
用于检测
constructor.prototype
是否存在于参数object
的原型链上。要自实现
instanceof
,就要了解这些特性:需要注意的是:不同上下文(比如网页中多个
<iframe>
)之间拥有不同的全局对象,可理解为不同的引用地址,因此会出现如下情况:因此,使用
instanceof
来判断是否为数组是不准确的,可看文章。三、实现
获取原型对象的方法:
实现如下:
The end.
The text was updated successfully, but these errors were encountered: