手写instanceof、手写new操作符

文章目录

  • [1 手写instanceof](#1 手写instanceof)
  • [2 手写new操作符](#2 手写new操作符)

1 手写instanceof

  • instanceof:用于判断构造函数的prototype属性是否出现在对象原型链中的任何位置
  • 实现步骤:
    1. 获取类型的原型。
    2. 获取对象的原型。
    3. 一直循环判断对象的原型是否等于构造函数的原型对象,直到对象原型为null。
javascript 复制代码
function myInstanceof(left, right) {
    let proto = Object.getPrototypeOf(left);
    let prototype = right.prototype;
    while (true) {
        if (proto == null) return false;
        if (proto === prototype) return true;
        proto = Object.getPrototypeOf(proto);
    }
}

2 手写new操作符

  • 调用new:
    1. 创建一个空对象。
    2. 将对象的原型设置为构造函数的prototype。
    3. 让构造函数的this指向这个对象,执行构造函数的代码,为这个新对象添加属性。
    4. 判断函数的返回值类型,如果是值类型,返回创建的对象,如果是引用类型,返回引用类型的对象。
javascript 复制代码
function myNew() {
    let newObject = null;
    let result = null;
    let constructor = Array.prototype.shift.call(arguments);
    if (typeof constructor !== "function") {
        console.error("type error");
        return;
    }
    newObject = Object.create(constructor.prototype);
    result = constructor.apply(newObject, arguments);
    let flag = result && (typeof result === "object" || typeof result === "function");
    return flag ? result : newObject;
}
myNew(构造函数, 初始化参数);
相关推荐
帅那个帅19 分钟前
PHP里面的抽象类和接口类
开发语言·php
咖啡の猫6 小时前
Python字典推导式
开发语言·python
leiming67 小时前
C++ vector容器
开发语言·c++·算法
SystickInt7 小时前
C语言 strcpy和memcpy 异同/区别
c语言·开发语言
CS Beginner7 小时前
【C语言】windows下编译mingw版本的glew库
c语言·开发语言·windows
FJW0208147 小时前
Python_work4
开发语言·python
多看书少吃饭8 小时前
从Vue到Nuxt.js
前端·javascript·vue.js
大学生资源网8 小时前
java毕业设计之儿童福利院管理系统的设计与实现(源码+)
java·开发语言·spring boot·mysql·毕业设计·源码·课程设计
JasmineWr8 小时前
JVM栈空间的使用和优化
java·开发语言
前端一小卒8 小时前
从 v5 到 v6:这次 Ant Design 升级真的香
前端·javascript