What is the NEW operator of JavaScript?

Xiaobian to share the new operator of JavaScript, I hope everyone will read this article, let us discuss together!

In the process of learning JavaScript, inevitable will encounter New operator, this time, it will come to the bottom of the roots, and it is also a deep understanding and memory. NS.

What is the new operator?

MDN is this defined New operator:

New operator creates an instance of a user-defined object type or a built-in object with constructor Example.

In this sentence we come to see a keyword: has a constructor . What does this mean? Let’s take a look at several examples:

 // Example 1Et Animal1 = function () {this.name = 1}; let animal = new animal1; // () It is equivalent to passing parameters // => animal1 {name: 1} // Example 2Let testobj = {} let t1 = new testobj; // => uncaupht typeerror: testobj is not a constructor copy code   
We can see that Example 1 successfully implemented

New statement, created an instance. Example 2 In NEW A {} Object When the error TYPEERROR: TESTOBJ IS NOT A Constructor , pointing out the target is not a constructor . Why can't the normal object can be executed new operator? Introduction to the ECMA specification:

IF TYPE (ArgumentIS NOT Object, Return False.

IF Argument Has A


    The constructor first is one subject, otherwise the condition
  • Secondly, the object must have
  • [[construct]] inside Method can be used as a constructor
  • We here

is an object, meeting the first condition, then obviously, it is definitely because { } No [[Construct]] This internal method is not available to the New operator. So we have already got


operator’s operational object, is it possible to see its role? The answer is: no! Let’s take another example: // Example 3ount Testobj = {Fn () {console.log (“Construction success!”)}}} Let t3 = new testobj.fn; / / => Uncaupht typeerror: testobj.fn is not a constructor copy code

? Why is the function that just successfully constructs? In fact, there is also a direct introduction in MDN:
  Methods Cannot Be Constructors! The Will throw a typerror if you try to instantiate them.  

method cannot be constructor

, if you try to create an instance of a method, you will throw a type error. This is said, but it’s not finished, this statement does not fully explain the principle, let’s see an example:

// Example 4Const Example = {Fn: function () {console .log (this);}, arrow: () => {Console.log (this);}, shorthand () {console.log (this);}}; new example.fn (); // fn} NEW EXAMPLE.ARROW (); // uncaught typeerror: example.Arrow is not a constructornew example.shorthand (); // uncaught typeerror: example.Shorthand is not a constructor replication code

Put this example, we have reviewed the ECMA specification, found that all functions depends on functionCreate
 when creating:   
FunctionCreate (Kind, Parameterlist, Body, Scope, Strict , Prototype)

i The Prototype Argument Was Not Passed, Then Let Prototype Be The Intrinsic Object% FunctionPrototype%. IF “Kind” Is Not Normal, Let Allockind BE “Non -CO”

The definition of this function can be seen that

  1. is only created when the type of
  2. Normal
  3. is created. It is a functionable function, otherwise he is not confessed.
In our example,


    The type of
  • shorthand is Method , so it is not a constructed function, which explains the “method of the method” said that the method cannot be used as a constructor “. New
  • Operators can operate, and finally you can look at its role (it’s not easy to tat).

What did the New operator achieve? Let’s take a simple example to see its role: function animal (name) {this.name = name; console.log (“Create Animal” );} let animal = new animal (“Rhubarm”); // Create Animalconsole.log (Animal.Name); // 大 黄 Animal.Prototype.SAY = Function () {Console.log (“MyName IS:” + THIS .name);} Animal.SAY (); // myname is: rhubarb copy code From this example to analyze, first we look at this sentence:

Let animal = new animal; copy code

can be seen, executing
 New  After the operator, we got a  Animal 
object, then we know, New

operator must have an object and return this object. Look at this code:

Function Animal (Name) {this.name = name; console.log (“create animal”);} Copy code
At the same time, we see the result, indeed output Create Animal

, we know, Animal function body is executed during this process, and incorporating parameters, So I executed our output statement. But there is still a sentence in our functions this.name = name Where is it? This is this: Console.log (animal.name); // Rubben copy code

 After performing a function, we discovered The  Name  value of the return object is the value we assign 
this , then it is not difficult to judge, in which

THIS is pointing to the newly created object . There is also a paragraph: Animal.Prototype.SAY = function () {console.log ("MyName is:" + this.name);} animal.say (); / / myName is: Raw Copy Code Animal Object call is a method of

animal function prototype, indicating
 Animal  In the prototype chain of  Animal 
, which layer is there?We verify:

Animal .__ proto __ === Animal.Prototype; // true copy code then we know, __ proto __

directly points to AnImal
  prototype . In addition, if we return to the body of the constructor in a value, see what happens: 

function Animal (name) {this.name = name; return 1 NEW Animal ("Test"); // Animal {name: "Test"} Copy code can be seen, directly ignore the return value, then we return an object test Test: Function Animal (Name) {this.Name = Name; return {};} new animal ("test"); // {} copy code

 We found that the object returned was overwritten by our return value. He roughly understands the core function of  New  operator. We make a summary. 

NEW Operations: Create a new object, will THIS

Binds to the newly created object
 Use the incoming parameter call constructor   
will be created


Point to constructor prototype
If the constructor does not explicitly return an object, return to the created object, otherwise returns an explicit returned object (as

{} )

Simulation to achieve a new operator

said so many theories, finally we personally do hand to achieve a new operator ~

  • VAR _mynew = function (constructor, … args) {// 1. Create a new object obj const object = {}; // 2. Bind this to the new object and use incoming parameter call functions //// Here is to get the first parameter, it is the incoming constructor // let constructor = array.prototype.shift.call (arguments); // Bind the simultaneous call function, … Expand the parameters into Let res = constructor.call (obj, … args) // 3. _Proto__ of the object of the object to point to the Prototype Obj .__ proto__ = constructor.prototype //4 of the constructor. Depending on the value returned according to the display. Res: RETURN RES INSTANCEOF OBJECT? RES: OBJ;} Copy code The above is a very well-understood version, we can simplify the following version:
  • Function _new (fn, … arg) {const obj = Object.create (fn.prototype); const res = fn.apply (obj, arg); ReturnRES: OBJ; copy code
  • Dachel! After reading this article, I believe that you have a certain understanding of the new operator of JavaScript. I want to know more related knowledge. Welcome to Tumi Yun Industry Information Channel, thank you for reading!
© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment