A summary of how named functions are called in JavaScript
- 2020-03-30 04:17:46
- OfStack
It was mentioned in a previous post (link: #). This article looks at the various ways in which named functions can be called.
1, ()
The most commonly used is the () operator to call/execute a function:
//The function fun1
function fun1() {
alert(' I got called ');
}
fun1();
//The argument function fun2
function fun2(param) {
alert(param);
}
fun2(' I got called ');
After ECMAScript3 is added, call and apply are added to Function.
2, call
//The function fun1
function fun1() {
alert(' I got called ');
}
fun1.call(null);
//The argument function fun2
function fun2(param) {
alert(param);
}
fun2.call(null,' I got called ')
3, apply
//The function fun1
function fun1() {
alert(' I got called ');
}
fun1.apply(null);
//The argument function fun2
function fun2(param) {
alert(param);
}
fun2.apply(null,[' I got called '])
Although call and apply can be used purely to call/execute functions, they are more used to change the context in which the function is executed.
4. New (not recommended)
//The function fun1
function fun1() {
alert(' I got called ');
}
new fun1();
//The argument function fun2
function fun2(param) {
alert(param);
}
new fun2(' I got called ')
The essence of new is to create/construct an instance of a class, where fun1 and fun2 are clearly not a class (no this, no prototype). But two functions do execute. This is a side effect of new.
There is no difference between the four methods in terms of the above method. But if the function returns a value, you may be disappointed when called in new.
//The function fun
with a return value
function fun() {
alert(' I got called ');
return "jack";
}
var c = new fun();
alert(c);//[object object], why not "jack"? < br / >
To such
//The function fun
with a return value
function fun() {
alert(' I got called ');
return {name:'jack'};
}
var c = new fun();
alert(c.name); //Jack, returns < br / > as normal
To summarize: when calling a function in new mode. If a return value exists, it will not be returned when the return value is a JavaScript built-in type (primitive type) such as String, Number, Boolean, etc. When the return value is an object, a function, an array, etc., it returns the object, function, array, etc.
What exactly does new fun() return when the return value is a built-in (primitive) type? The next article will discuss the details of new mode invocation.