What exactly does new() in js do

We often use the new operator in our daily development to see what it does;

And its implementation principle In javascript, there are two ways to create objects: ① object literal ② new expression

// 字面量形式
let person = {
   name: '王新焱',
   age: 33
}

// 构造函数形式 (new)
function Person(name, age) {
  this.name = name
  this.age = age
}

let  person  = new Person()

The disadvantage of object literal writing is that every time a new object is created, a complete definition statement needs to be written, which is inconvenient to create a large number of objects of the same type, and is not conducive to the use of advanced features such as inheritance.

The new expression is used in conjunction with the constructor, and a new constructor is used to inherit the attributes of the constructor.

To create a new instance of Person, the new operator must be used. Calling the constructor in this way will go through the following 4 steps:
①. Create an empty simple JavaScript object (ie {})
②. Add the attribute __proto__ to the newly created object, and link the attribute to the prototype object of the constructor
③ . Use the newly created object as the context of this
④. Return a new object

What is a constructor?
A function that instantiates an object through the new function name is called a constructor. There is not much difference between a constructor and an ordinary function. In order to distinguish the function whose first letter of the function name is capitalized as a constructor, the main function is that the constructor creates an object through the new keyword and adds properties and methods to the initialized object.


Constructors are technically regular functions. But there are two conventions:

①. Their names start with a capital letter.
②. They can only be executed by the "new" operator.

Here is an example constructor:


// 构造函数Person

function Person(name, age) {
  this.name = name
  this.age = age
}

let p = new Person('王新焱', 33)

console.log(p) // { name: '王新焱', age: 33 }

p.constructor === Person // true

p.__proto__ === Person.prototype // true

Guess you like

Origin blog.csdn.net/qq_34402069/article/details/129544960