1. The () parentheses operator is usually used to call a function.
CopyCode The 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. CallCopy 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. ApplyCopy 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], 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.