The previous article mentioned multiple call methods for anonymous functions. In this article, let's take a look at the multiple call methods of the named function.
1 ,()
The () operator is commonly used to call/execute a function.
// Fun1function fun1 () {alert ('I was called');} fun1 (); // fun2function fun2 (PARAM) {alert (PARAM);} fun2 ('I called ');
After ecmascript3 is added to the function with call and apply, the following two methods are available:
2. Call
// Fun1function fun1 () {alert ('I was called');} fun1.call (null); // fun2function fun2 (PARAM) {alert (PARAM);} fun2.call (null, 'I called ')
3. Apply
// Fun1function fun1 () {alert ('I was called');} fun1.apply (null); // fun2function fun2 (PARAM) {alert (PARAM);} fun2.apply (null, ['I called'])
Although call and apply can be used to call/execute functions, they are used to change the context of function execution.
4. New(This method is not recommended.)
// Fun1function fun1 () {alert ('I was called');} new fun1 (); // fun2function fun2 (PARAM) {alert (PARAM);} new fun2 ('I called ')
The essence of New is to create/construct an instance of a class. The defined fun1 and fun2 are obviously not a class (without this, there is no prototype ). But the two functions are actually executed. This is a side effect of new.
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.
// Function funfunction fun () {alert ('I was called'); Return "Jack";} var c = new fun (); alert (C ); // [object]. Why is it not "Jack "?
Change to this
// Function funfunction fun () {alert ('I was called'); Return {Name: 'jack'};} var c = new fun (); alert (C. name); // Jack, and the returned result is normal.
Conclusion: 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 directly 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.