手写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(构造函数, 初始化参数);
相关推荐
不可能的是7 分钟前
从 /simplify 指令深挖 Claude Code 多 Agent 协同机制
javascript
Rabitebla9 分钟前
vector 的骨架:三根指针、模板陷阱与迭代器失效的第一现场
开发语言·数据结构·c++·算法
时空系10 分钟前
第7篇:功能——打造你的工具箱 Rust中文编程
开发语言·网络·rust
csbysj202018 分钟前
CSS !important:深度解析与最佳实践
开发语言
初心未改HD23 分钟前
Go语言测试与Benchmark:测试驱动开发的实践指南
开发语言·golang
chxii31 分钟前
lua流程控制语句和table(表)数据结构
开发语言·junit·lua
Rkgua35 分钟前
事件流模型是什么和DOM事件模型等关系
javascript
逻辑驱动的ken38 分钟前
Java高频面试考点场景题20
java·开发语言·深度学习·面试·职场和发展
W.A委员会39 分钟前
多行溢出在末尾添加省略号
开发语言·javascript·css
wjs202442 分钟前
RSS Item 元素:深入解析与使用指南
开发语言