返回

JavaScript实现new的原理

前端

揭秘JavaScript中的new运算符

创建新对象

当我们使用new运算符时,它首先会创建一个新对象。这个对象是根据构造函数的原型对象创建的。原型对象是构造函数的一个属性,它包含了构造函数的所有属性和方法。

function Person(name) {
  this.name = name;
}

const person1 = new Person('John');

console.log(person1); // {name: 'John'}

将构造函数的作用域赋值给新对象

一旦新对象被创建,构造函数的作用域就会被赋值给这个新对象。这意味着this现在指向这个新对象。

function Person(name) {
  console.log(this); // 指向新创建的对象
  this.name = name;
}

const person1 = new Person('John');

执行构造函数中的代码

在构造函数的作用域被赋值给新对象之后,构造函数中的代码就会被执行。这包括为新对象添加属性和方法。

function Person(name) {
  this.name = name;

  this.greet = function() {
    console.log(`Hello, my name is ${this.name}`);
  };
}

const person1 = new Person('John');

person1.greet(); // Hello, my name is John

返回新对象

最后,new运算符会返回新对象。这个对象包含了在构造函数中添加的所有属性和方法。

function Person(name) {
  this.name = name;

  this.greet = function() {
    console.log(`Hello, my name is ${this.name}`);
  };

  return this;
}

const person1 = new Person('John');

console.log(person1); // {name: 'John', greet: function}

this关键字

this关键字是一个特殊的关键字,它指向当前正在执行的函数或方法的对象。在构造函数中,this关键字指向新创建的对象。这意味着我们可以使用this关键字来访问和修改新对象中的属性和方法。

function Person(name) {
  this.name = name;

  this.greet = function() {
    console.log(`Hello, my name is ${this.name}`);
  };
}

const person1 = new Person('John');

person1.greet(); // Hello, my name is John

总结

new运算符是JavaScript中创建一个新对象的一种方式。它通过创建一个新对象,将构造函数的作用域赋值给这个新对象,执行构造函数中的代码,然后返回这个新对象来实现。this关键字指向当前正在执行的函数或方法的对象,在构造函数中,this关键字指向新创建的对象。