大漠的博客

可远程工作的全栈工程师 | 支持北美/欧洲时区

javascript中new构造函数时发生了什么

在 JavaScript 中,使用 new 操作符调用一个函数(称为构造函数)时,会执行以下四个关键步骤:

1. 创建一个新的空对象

JavaScript 引擎首先创建一个全新的空对象:

const newObj = {};

2. 设置新对象的原型([[Prototype]])

将这个新对象的内部原型([[Prototype]],可通过 __proto__Object.getPrototypeOf() 访问)链接到构造函数的 prototype 属性:

newObj.__proto__ = Constructor.prototype;

这意味着新对象可以访问构造函数原型上的所有属性和方法。

3. 执行构造函数,并将 this 绑定到新对象

构造函数体内的代码会被执行,且其中的 this 指向刚刚创建的新对象。构造函数通常会为 this 添加属性或方法:

Constructor.apply(newObj, args);

例如:

function Person(name) {
  this.name = name; // this 指向新对象
}

4. 返回新对象(除非构造函数显式返回一个对象)

  • 如果构造函数 没有显式返回值,或者返回的是原始类型(如 stringnumberboolean 等),则自动返回新创建的对象。
  • 如果构造函数 显式返回一个对象,则返回该对象,而不是新创建的对象。

示例:

function Foo() {
  this.a = 1;
  return { b: 2 }; // 返回这个对象,而不是 this
}

const obj = new Foo();
console.log(obj); // { b: 2 }

但如果返回的是原始值:

function Bar() {
  this.a = 1;
  return 42; // 被忽略
}

const obj = new Bar();
console.log(obj); // { a: 1 }

总结:new 的行为可模拟如下:

function newInstance(Constructor,...args){
  // 1.Object.create创建一个对象,对象的__proto__指向Constructor.prototype
  const instance = Object.create(Constructor.prototype)
  // 2.改变Constructor内部的this指向,使instance拥有构造函数的属性
  const res =  Constructor.apply(instance,args)
  // 3.判断如果返回值是对象或者函数,就返回result,否则返回instance
  return typeof res === "object" || typeof res === "function" ? res : instance;
}

思考部分(ps:没事找事部分):

1.模拟new行为的函数newInstance中,构造函数的属性是怎么注入到新对象中的?

2.new (new MyFunc().constructor)()是否可执行?

Tags:

发表回复

Your email address will not be published. Required fields are marked *.

*
*

技术栈

Nestjs,PHP,Angular,React,Vue

联系我

地址
123 Main Street
New York, NY 10001

营业时间
星期一—五:9:00–17:00
星期六—日:11:00–15:00