new 操作符的原理及手写

什么是 new ?

在JavaScript中,new 是一个用于创建对象实例的关键字。它用于调用构造函数,并返回一个新的对象。

使用

  • 使用 new 创建的对象,可以访问构造函数及其原型链上的属性和方法。
js 复制代码
function User(name) {
  this.name = name;
  this.isAdmin = false;
}

let user = new User("Jack");

console.log(user.name); // Jack
user.isAdmin(); // yes
  • 通常,构造器没有 return 语句。它们的任务是将所有必要的东西写入 this,并自动转换为结果。

  • 但是,如果这有一个 return 语句,那么规则就简单了:

    • 如果 return 返回的是一个对象,则返回这个对象,而不是 this
    • 如果 return 返回的是一个原始类型,则忽略。
js 复制代码
function BigUser(name) {

  this.name = name;

  return { name: "Godzilla" };  // <-- 返回这个对象
}

const user = new BigUser("John");
console.log(user.name);  // Godzilla,得到了那个对象
  • 这里有一个 return 为空的例子(或者我们可以在它之后放置一个原始类型,没有什么影响):
js 复制代码
function SmallUser(name) {

  this.name = name;

  return; // <-- 返回 this
}

const user = new SmallUser("John");
console.log(user.name)  // John

实现原理

  1. 创建一个新对象
  2. 新对象的原型指向构造函数的原型对象
  3. 构造函数中的this指向该对象(也就是为这个对象添加属性和方法)
  4. 构造函数返回的是对象则返回它,如果不是则返回一开始创建的新对象

手写 new 操作符

js 复制代码
function myNew(constructor,...args){
    // 创建一个新对象,原型指向构造函数的原型对象
    const obj = Object.create(constructor.prototype);
    // 将构造函数的this指向新对象。如果构造函数没有返回对象时,result为undefined,this指向obj;如果构造函数返回了一个对象,this指向返回的对象
    const result = constructor.apply(obj,args);
    // 如果构造函数返回了一个对象,则返回该对象;否则,返回新对象
    return result instanceof Object ? result : obj; 
}
  • 测试:
js 复制代码
function myNew(constructor,...args){
    // 创建一个新对象,原型指向构造函数的原型对象
    const obj = Object.create(constructor.prototype);
    // 将构造函数的this指向新对象。如果构造函数没有返回对象时,result为undefined,this指向obj;如果构造函数返回了一个对象,this指向返回的对象
    const result = constructor.apply(obj,args);
    // 如果构造函数返回了一个对象,则返回该对象;否则,返回新对象
    return result instanceof Object ? result : obj; 
}


function User(name, age) {
    this.name = name;
    this.age = age;
}

User.prototype.say = function () {
    console.log(this.name)
}

const p = myNew(User, "qqq", 20)
console.log(p) // User {name: 'qqq', age: 20}
p.say() // qqq

如有问题欢迎在评论区讨论,一起进步!

相关推荐
崔庆才丨静觅8 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60619 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了9 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅9 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅9 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅10 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment10 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅10 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊10 小时前
jwt介绍
前端