1. The () parentheses operator is usually used to call a function.
Copy codeThe Code is as follows:
// Fun1
Function fun1 (){
Alert ('I was called ');
}
Fun1 ()
// Fun2 with Parameters
Function fun2 (param ){
Alert (param );
}
Fun2 ('I was called ')
After ECMAScript3 is added to the Function with call and apply, the following two methods are available:
2. call
Copy codeThe Code is as follows:
// Fun1
Function fun1 (){
Alert ('I was called ');
}
Fun1.call (null );
// Fun2 with Parameters
Function fun2 (param ){
Alert (param );
}
Fun2.call (null, 'I was called ')
3. apply
Copy codeThe Code is as follows:
// Fun1
Function fun1 (){
Alert ('I was called ');
}
Fun1.apply (null );
// Fun2 with Parameters
Function fun2 (param ){
Alert (param );
}
Fun2.apply (null, ['I was called'])
4. new (this method is not recommended)
Copy codeThe Code is as follows:
// Fun1
Function fun1 (){
Alert ('I was called ');
}
New fun1 ();
// Fun2 with Parameters
Function fun2 (param ){
Alert (param );
}
New fun2 ('I was called ')
OK. From the above call method, there is no difference in the execution results of the four methods. However, if a function returns a value, calling the new method may disappoint you.
Copy codeThe Code is as follows:
// Function fun with returned values
Function fun (){
Alert ('I was called ');
Return "jack ";
}
Var c = new fun ();
Alert (c); // [object Object], why not "jack "?
This is the case,
Copy codeThe Code is as follows:
// Function fun with returned values
Function fun (){
Alert ('I was called ');
Return {name: 'jack '};
}
Var c = new fun ();
Alert (c. name); // jack, returns again normally
Now, let's sum up: when calling a function using the new method. If a return value exists, this value is not returned when the returned value is a built-in javascript type (basic type) such as String, Number, or Boolean; when the returned value is an object, function, array, or other object types, this object, function, and array are returned.
When the returned value is a built-in type (basic type), what does new fun () return? The next article will discuss the details of the new method call.