1. function has return value
$ (function () {
function Person (name,age,job) {
var o=new Object ();
O.name=name;
O.age=age;
O.job=job;
O.sayhi=function () {
Console.log (this.name);
}
return o;
}
var people= new person (' Xiaowang ', ' Developer ');//new
People.sayhi ();
var people1= person (' Xiaowang ', ' Developer ');
People1.sayhi ();
});
The results of the New keyword call and the direct call are the same.
The person function creates an object, initializes the object with the appropriate properties and methods, and then returns the object, which is exactly the same as the factory pattern, except that the new operator is used and the wrapper function is called the constructor.
2. If the function does not return a value
$ (function () {
function Person (name,age,job) {
var o=new Object ();
This.name=name;
This.age=age;
This.job=job;
This.sayhi=function () {
Console.log (this.name);
}
return o;
}
var people= new person (' Xiaowang ', ' Developer ');//new
People.sayhi ();
var people1= person (' Xiaowang ', ' Developer ');
People1.sayhi ();
});
Note: The constructor returns the new object instance by default, without returning a value.
The new call works, and a direct call will fail
3: If the return value is a function
$ (function () {
function person () {
This.name= ' test ';
return function () {return true};
}
var people= new Person ();//Construction Object
var people1= person ();//Direct call
Console.log (PEOPLE==PEOPLE1);
Console.log (PEOPLE===PEOPLE1);
});
Although the browser results are the same, the comparison results are false, because JavaScript compares object and function based on reference types.
4. If the return value is a value type (for example: number)
$ (function () {
function person () {
This.name= ' test ';
Return 2;//function () {return true};
}
var people= new Person ();//Construction Object
var people1= person ();//Direct call
Console.log (PEOPLE==PEOPLE1);
Console.log (PEOPLE===PEOPLE1);
});
The results of the comparison found that all were false.
So I guess.
If the function returns a value type (number, String, Boolean) in the general sense, the new function returns an instance object of the function, and if the function returns a reference type (object, Array, function), Although the new function is equivalent to the result of a direct call to a function, it is two different processes, one constructed and one function called.
Javascript uses the new keyword to invoke the difference between a function and a direct call to a function