There is a previous article that mentions the various invocation modes of anonymous functions. This article looks at the various invocation modes of the named function.
1, ()
The most commonly used is the () operator to invoke/execute a function:
Copy Code code as follows:
Non-parametric function fun1
function Fun1 () {
Alert (' I was called out ');
}
Fun1 ();
Fun2 with parameter function
function fun2 (param) {
alert (param);
}
Fun2 (' I was called out ');
After adding the call and apply to the function after ECMASCRIPT3, there are two of these.
2, call
Copy Code code as follows:
Non-parametric function fun1
function Fun1 () {
Alert (' I was called out ');
}
Fun1.call (NULL);
Fun2 with parameter function
function fun2 (param) {
alert (param);
}
Fun2.call (NULL, ' I was called ')
3, apply
Copy Code code as follows:
Non-parametric function fun1
function Fun1 () {
Alert (' I was called out ');
}
Fun1.apply (NULL);
Fun2 with parameter function
function fun2 (param) {
alert (param);
}
Fun2.apply (null,[' I was called '])
Although call,apply can be used purely to invoke/execute functions, they are more often used to alter the context of function execution.
4, new (not recommended to use this way OH)
Copy Code code as follows:
Non-parametric function fun1
function Fun1 () {
Alert (' I was called out ');
}
New Fun1 ();
Fun2 with parameter function
function fun2 (param) {
alert (param);
}
New Fun2 (' I was called ')
The essence of new is to create/construct an instance of a class, where the definition of fun1,fun2 is obviously not a class (no this, no prototype). But two functions did execute. This is the side effect of new.
There is no difference between the four ways of executing the results from the way they are called. But if the function has a return value, it may be a bit disappointing to call it in new mode.
Copy Code code as follows:
Functions that have return values fun
function Fun () {
Alert (' I was called out ');
return "Jack";
}
var C = new Fun ();
alert (c);//[object object] Why not "Jack"?
Change it.
Copy Code code as follows:
Functions that have return values fun
function Fun () {
Alert (' I was called out ');
return {name: ' Jack '};
}
var C = new Fun ();
alert (c.name); Jack, it's back to normal.
Summary: When calling a function in the new way. If there is a return value, this value is not returned when the return value is a built-in type of JavaScript (the base type), such as a string, numeric (number), Boolean (Boolean), and so on, which is returned directly when the return value is an object type, a function, an array, and so on. Functions, arrays.
When the return value is a built-in type (the base type), what does the new fun () return? The next article will discuss the details of the new method call.