Difference between using new in javascript and not using instantiated objects, javascriptnew
Let's first look at an instance.
function Me(name,age,job){ this.name = name; this.age = age; this.job = job;}
What are the differences between the following two ways of instantiating objects?
var mefun1 = new Me('fei','20','it');var mefun2 = Me('fei','20','it');
Simply put
The first type is the constructor, that is, the constructor Function is called through the new operator to create a Function.
The second method is not instantiation, but to call a function to assign the return value to the variable.
Extension
There are no real classes in JavaScript, but there are constructors and new operators in JavaScript. The constructor is used to initialize attributes and values for an instance object. Any JavaScript function can be used as a constructor. The constructor must use the new operator as the prefix to create a new instance.
The new operator changes the execution context of the function and the behavior of the return Statement. In fact, the use of new and constructor is similar to the traditional implementation of the class language:
// Instantiate a Mevar alice = new Me ('Alice ', 18, 'CODER'); // check the instance assert (alice instanceof Me );
The name of the constructor is usually separated from that of a common function by using the camper name method with an uppercase letter.
A habit.
// Do not do this! Me ('Alice ', 18, 'CODER'); // => undefined
This function will only return undefined, and the execution context is a window (global) object. Three global variables named name, age, and job are inadvertently created. Do not discard the new Keyword when calling the constructor.
When the new keyword is used to call the constructor, the execution context changes from the Global Object (window) to an empty context, which represents the new instance. Therefore, this keyword points to the currently created instance. Although it seems a bit difficult to understand, the implementation of built-in class mechanisms in other languages is also true.
By default, if no content is returned in your constructor, this -- current context is returned.
Otherwise, any non-original type value is returned.
The above is all the content of this article. I hope you will like it.