手写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(构造函数, 初始化参数);
相关推荐
一晌小贪欢5 分钟前
Python爬虫第7课:多线程与异步爬虫技术
开发语言·爬虫·python·网络爬虫·python爬虫·python3
ftpeak14 分钟前
《Cargo 参考手册》第二十二章:发布命令
开发语言·rust
luckyPian28 分钟前
学习go语言
开发语言·学习·golang
祁同伟.1 小时前
【C++】多态
开发语言·c++
朱嘉鼎2 小时前
C语言之可变参函数
c语言·开发语言
aesthetician3 小时前
Node.js v25 重磅发布!革新与飞跃:深入探索 JavaScript 运行时的未来
javascript·node.js·vim
北冥湖畔的燕雀5 小时前
C++泛型编程(函数模板以及类模板)
开发语言·c++
demi_meng7 小时前
reactNative 遇到的问题记录
javascript·react native·react.js
QX_hao7 小时前
【Go】--map和struct数据类型
开发语言·后端·golang
你好,我叫C小白7 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while