Let’s look at an example first
function Me(name,age,job){ this.name = name; this.age = age; this.job = job; }
What is the difference between the following two methods of instantiating objects?
var mefun1 = new Me('fei','20','it'); var mefun2 = Me('fei','20','it');
Simply put
The first is the constructor function, that is, calling the constructor Function through the new operator to create a function
The second method is not instantiation, but just calls the function and assigns the return value to the variable.
Expand it again
There are no real classes in JavaScript, but there are constructors and new operators in JavaScript. The constructor is used to initialize the properties and values of the instance object. Any JavaScript function can be used as a constructor, and the constructor must be prefixed with the new operator to create a new instance.
Thenew operator changes the execution context of the function and also changes the behavior of the return statement. In fact, using new and constructors is very similar to traditional languages that implement classes:
// 实例化一个Me var alice = new Me('alice', 18, 'Coder'); // 检查这个实例 assert( alice instanceof Me );
The naming of constructors usually uses camel case naming, with the first letter capitalized, to distinguish it from ordinary functions. This is
An idiomatic usage.
// 不要这么做! Me('alice', 18, 'Coder'); //=> undefined
This function will only return undefined, and the execution context is the window (global) object, and three global variables name, age, and job are inadvertently created. Don't lose the new keyword when calling the constructor.
When the constructor is called using the new keyword, the execution context changes from the global object (window) to an empty context, which represents the newly generated instance. Therefore, the this keyword points to the currently created instance. Although it is a bit confusing to understand, the same is true for the implementation of built-in class mechanisms in other languages.
By default, if your constructor returns nothing, it will return this - the current context.
Otherwise, return any non-primitive type value.
The above is the entire content of this article, I hope you all like it.