手写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(构造函数, 初始化参数);
相关推荐
栈溢出了13 小时前
LangGraph State 学习笔记
开发语言·人工智能·python
HEJOO913 小时前
Go 语言结构体定义与实例详解
开发语言·算法·golang
(Charon)13 小时前
【C++面试】手写智能指针(一):从unique_ptr理解独占所有权与移动语义
开发语言·c++
Brilliantwxx13 小时前
【STM32】 DMA 源码分析与实战(下):DMA 收发状态机与 HAL 分层
android·开发语言·stm32·单片机·嵌入式硬件·mcu
Ai-_Man13 小时前
请问豆包的智能体聊天记录该怎么弄
开发语言·前端·javascript·人工智能·小程序·ecmascript·电脑
এ慕ོ冬℘゜13 小时前
es6基础知识
前端·javascript·es6
言乐613 小时前
Python根据关联词搜索模型
开发语言·人工智能·python·机器学习·django
纪念 22914 小时前
C++ string(一)
android·开发语言·c++
一木 之林14 小时前
阿里云百炼与通义千问接入
开发语言·php
纪念 22914 小时前
C++算法(二)
开发语言·c++·算法