In the world of JavaScript, there are many ways to define functions, which is a reflection of JavaScript flexibility, but it is this reason that makes beginners confused, especially for students who do not have a language foundation. As the saying goes, all the roads lead to Rome, but if there are too many roads, it will make the traveler at a loss because he doesn’t know which road is the right way to go. Haha, I’m talking nonsense, and I’ll talk less, read the code first:
The code copy is as follows:
/*The first method uses function statement, the format is as follows*/
function fn(){
alert("This is the function statement for function definition");
}
fn();
/*The second method, use the Function() constructor to clone the function*/
var F = new Function("a","b","alert(a+b)");
F(a,b);
In fact, it is equivalent to the following code:
function F(a,b){
alert(a+b);
}
/*The third method is to use the function to directly count*/
var zhenn = function(){
alert("zhen");
}
zhenn();
Among them, the methods of using "function statements" and using "function direct quantity" to define functions seem to be more common and easy to understand, so I won't say much about it here. It is generally rarely used to clone functions using the Function() constructor, because a function usually consists of multiple statements. If they are passed as a string as a parameter, it will inevitably make the code readability poor.
Let me mention the constructor by the way here. In fact, from a literal perspective, the constructor seems to be a function. In fact, it is not a function, but just a function model. To give an inappropriate example, the constructor is equivalent to a newly assembled car. Whether it is far or close, it is a car, but it has not been refueled yet (represents a necessary step before use), so it cannot start. If you want the car to drive normally, you must add oil to it. In fact, this process is equivalent to instantiation of the constructor, otherwise it will not run normally! See the following example:
The code copy is as follows:
function Fn(){ //Define the constructor
this.elem ="Here is the function() constructor to define the function, haha";
this.fn = function(){
alert("This is to define the function using the function() constructor, hehe");
}
}
var f = new Fn(); //Instantiation
alert(f.elem);
f.fn();