The difference between using new in javascript and not using instantiated objects

  • 2020-06-19 09:41:27
  • OfStack

So let's look at an example


function Me(name,age,job){
  this.name = name;
  this.age = age;
  this.job = job;
}

What is the difference between these two ways of instantiating objects?


var mefun1 = new Me('fei','20','it');
var mefun2 = Me('fei','20','it');

In simple terms

The first is the constructor, which creates the function by calling the constructor Function via the new operator
The second is not instantiation, but simply calls a function to assign the return value to a variable.

To extend the

There are no real classes in JavaScript, but there are constructors and the new operator in JavaScript. Constructors are used to initialize properties and values to an instance object. Any JavaScript function can be used as a constructor, which must be prefixed with the new operator to create a new instance.

The new operator changes the execution context of the function and the behavior of the return statement. In fact, using new and constructors is very similar to traditional languages that implement classes:


//  instantiation 1 a Me
var alice = new Me('alice', 18, 'Coder');
//  Check this instance 
assert( alice instanceof Me );

Constructors are usually named using the hump notation, capitalized to distinguish them from normal functions
1.


//  Don't do it !
Me('alice', 18, 'Coder'); //=> undefined

This function returns only undefined, and the execution context is an window (global) object, inadvertently creating three global variables name,age,job. Don't drop the new keyword when you call the constructor.

When the constructor is invoked using the new keyword, the execution context changes from the global object (window) to an empty context that represents the newly generated instance. Therefore, the this keyword points to the currently created instance. Although a little convoluted to understand, the same is true of implementations of built-in class mechanisms in other languages.

By default, if your constructor returns nothing, it returns this -- the current context.

Otherwise, it returns any value that is not of primitive type.

This is the end of this article, I hope you enjoy it.


Related articles: