手写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(构造函数, 初始化参数);
相关推荐
Larry_Yanan8 小时前
Qt多进程(三)QLocalSocket
开发语言·c++·qt·ui
醒过来摸鱼8 小时前
Java classloader
java·开发语言·python
superman超哥8 小时前
仓颉语言中元组的使用:深度剖析与工程实践
c语言·开发语言·c++·python·仓颉
小鸡吃米…8 小时前
Python - 继承
开发语言·python
D_C_tyu8 小时前
Vue3 + Element Plus | el-table 表格获取排序后的数据
javascript·vue.js·elementui
JIngJaneIL8 小时前
基于java+ vue农产投入线上管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
祁思妙想8 小时前
Python中的FastAPI框架的设计特点和性能优势
开发语言·python·fastapi
唐装鼠8 小时前
rust自动调用Deref(deepseek)
开发语言·算法·rust
Lucas555555559 小时前
现代C++四十不惑:AI时代系统软件的基石与新征程
开发语言·c++·人工智能
源代码•宸9 小时前
goframe框架签到系统项目(BITFIELD 命令详解、Redis Key 设计、goframe 框架教程、安装MySQL)
开发语言·数据库·经验分享·redis·后端·mysql·golang