Home > Article > Web Front-end > Three ways to define functions in JavaScript_javascript tips
In the world of JavaScript, there are many ways to define functions, which is a reflection of the flexibility of JavaScript. However, it is precisely this reason that makes beginners confused, especially for students who have no language foundation. As the saying goes, all roads lead to Rome, but if there are too many roads, the traveler will be at a loss because he does not know which road is the right way to take. Haha, this is a long article, let’s not talk about it, let’s look at the code first:
/*The second method is to use the Function() constructor to clone the function*/
var F = new Function("a","b","alert(a b)");
F(a,b);
is actually equivalent to the following code:
function F(a,b){
alert(a b);
}
/*The third method is to use function literals*/
var zhenn = function(){
alert("zhenn");
}
zhenn();
Among them, the methods of using "function statements" and "function literals" to define functions seem to be more common and easier to understand, so I won't go into details here. Clone functions using the Function() constructor are generally rarely used because a function usually consists of multiple statements. If they are passed as parameters in the form of strings, it will inevitably make the code less readable.
Let me mention the constructor here by the way. In fact, literally, 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. No matter it is viewed from a distance or up close, it is still a car, but it has not yet been refueled (representing a necessary step before use), so it and cannot be started. If you want this car to drive normally, you must add oil to it. In fact, this process is equivalent to the instantiation of the constructor, otherwise it will not run normally! Look at this example: