An earlier article mentioned various ways of calling anonymous functions. This article takes a look at the various ways to call named functions.
1. ()
The most commonly used function is to call/execute a function:
The code copy is as follows:
// No parameter function fun1
function fun1() {
alert('I'm called');
}
fun1();
// Parameter function fun2
function fun2(param) {
alert(param);
}
fun2('I'm called');
After ECMAScript3, call and apply function, there are two types of functions.
2. Call
The code copy is as follows:
// No parameter function fun1
function fun1() {
alert('I'm called');
}
fun1.call(null);
// Parameter function fun2
function fun2(param) {
alert(param);
}
fun2.call(null,'I'm called')
3. apply
The code copy is as follows:
// No parameter function fun1
function fun1() {
alert('I'm called');
}
fun1.apply(null);
// Parameter function fun2
function fun2(param) {
alert(param);
}
fun2.apply(null,['I'm called'])
Although call, apply can be used purely to call/execute functions, they are more used to change the context of function execution.
4. new (This method is not recommended)
The code copy is as follows:
// No parameter function fun1
function fun1() {
alert('I'm called');
}
new fun1();
// Parameter function fun2
function fun2(param) {
alert(param);
}
new fun2('I'm called')
The essence of new is to create/construct an instance of a class. The fun1 and fun2 defined here are obviously not a class (no this, no prototype). But both functions did execute. This is a side effect of new.
From the above call method, there is no difference in the execution results of the four methods. But if the function has a return value, it may disappoint you when calling it in the new way.
The code copy is as follows:
// Function fun with return value
function fun() {
alert('I'm called');
return "jack";
}
var c = new fun();
alert(c);//[object Object], why not "jack"?
Change it to this
The code copy is as follows:
// Function fun with return value
function fun() {
alert('I'm called');
return {name:'jack'};
}
var c = new fun();
alert(c.name); //jack, it returned normally
To summarize: When calling a function in new way. If there is a return value, the value will not be returned when the return value is a built-in type (base type) of JavaScript such as string (String), number (Number), Boolean, etc.; when the return value is an object type, the object, function, and array will be directly returned.
When the return value is a built-in type (base type), what exactly does new fun() return? The next article will discuss the details of new method calls.