preface

Javascript, like other high-level languages, has the new keyword. We used to know that new is used to create an instance object of a class, but in JS everything is an object, why do we need the new keyword? The new operator in JS is used to create an instance of a user-defined object type or of a built-in object with a constructor. Next, this article will take you through implementing a new keyword…

The original new

Let’s start by writing a new object by hand:

Function person(name, age) {this.name = name this.age = age} let p = new person(' blank ', 12) console.log(p) // person {name: 'bran ', age: 12}Copy the code

Print result:

It can be seen from the print result:

When an object is instantiated with the new keyword, an empty object p is first created, and this empty object contains two properties, name and age, corresponding to two properties in the constructor. We also know that the instantiated object p is inherited from Person.prototype, so now we can summarize what the new keyword does inside the instantiated object.

  1. The new keyword does three things internally (given its constructor) : Create an empty object and make it inherit constructor. Prototype;
  2. Execute the constructor and point this to the new object you just created;
  3. Returns a new object;

Encapsulate a function that implements the new keyword

Once we know the inner workings of the new keyword, we can encapsulate an objectFactory function that implements the new keyword.

The objectFactory function takes the following arguments:

The first argument: Constructor name;

The second and subsequent arguments: arguments to the constructor;

Key points:

  • New creates a new object;
  • The new object needs to have access to the constructor’s properties, so it needs to respecify its prototype;
  • Constructors may display returns;

Manual tear code:

function objectFactory() { var obj = new Object(); Constructor = [].shift.call(arguments); // arguments A list of arguments to be called by constructor. obj.__proto__ = Constructor.prototype; var ret = Constructor.apply(obj, arguments); / / ret | | obj so write here consider the constructor display of return null return typeof ret = = = 'object'? ret || obj : obj; };Copy the code
  1. New creates a new object;

  2. Take the first argument of the passed argument, the Constructor;

  3. Execute the constructor and point this to the created empty object obj;

  4. The arguments passed to the constructor are executed in the obj context;

  5. If the constructor returns an object, it returns the object directly.

Use:

Function person(name, age) {this.name = name this.age = age} let p = objectFactory(person, 'bran ', 12) console.log(p) // {name: 'bran ', age: 12}Copy the code

Print result:

The final print returned is obviously the same, with the new keyword implemented.

conclusion

The above is what I want to introduce about the implementation of the new keyword content, I hope to help you.