Let's take a look at some examples first
function Me (name,age,job) {
this.name = name;
This.age = age;
This.job = job;
}
What is the difference between the following two kinds of instantiated object methods?
var mefun1 = new Me (' Fei ', ' m ', ' it ');
var mefun2 = Me (' Fei ', ' m ', ' it ');
To put it simply,
The first is a constructor that calls the constructor function with the new operator to create a function
The second is not instantiated, just calling the function to assign the return value to the variable.
And then expand the
There are no real classes in JavaScript, but there are constructors and new operators in JavaScript. Constructors are used to initialize the properties and values of an instance object. Any JavaScript function can be used as a constructor, and the constructor must use the new operator as a prefix to create a fresh instance.
The new operator changes the execution context of the function and changes the behavior of the return statement. In fact, using new and constructors is very similar to the traditional language that implements the class:
Instantiate a me-
var alice = new Me (' Alice ', ', ' coder ');
Check this instance
assert (Alice instanceof Me);
The name of a constructor usually uses the hump-naming method, the first-letter capitalization, which distinguishes it from the normal function, which is
A customary use.
Don't do this!
Me (' Alice ', ' Coder '); => undefined
This function only returns undefined, and the execution context is a window (global) object that unintentionally creates 3 global variable name,age,job. Do not discard the new keyword when calling the constructor.
When the constructor is invoked using the New keyword, the execution context becomes an empty context from the Global Object (window), which represents the newly generated instance. Therefore, the This keyword points to the currently created instance. Although the understanding is somewhat around, in fact the implementation of the built-in class mechanism in other languages is the same.
By default, if nothing is returned in your constructor, the current context of this--is returned.
Otherwise, the value of any non original type is returned.
The above mentioned is the entire content of this article, I hope you can enjoy.