A previous article mentioned Multiple ways to call anonymous functions. This article looks at the various ways to call named functions.
1, ()
The most commonly used one is the () operator to call/execute a function:
After ECMAScript3 added call and apply to Function, there are the following two types.
2. call
3. apply
Although call and apply can be purely used to call/execute functions, they are more used to change the context of function execution.
4. new (this method is not recommended)
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 calling methods, there is no difference in the execution results of the four methods. But if the function has a return value, you may be a little disappointed when calling it with new.
Change it to this
To summarize: when calling a function using new method. If there is a return value, when the return value is a built-in type (basic type) of JavaScript such as String, Number, Boolean, etc., the value will not be returned; when the return value is an object, the function , array and other object types, the object, function, array will be returned directly.
When the return value is a built-in type (basic type), what exactly does new fun() return? The next article will discuss the details of the new method call.