Home >Web Front-end >JS Tutorial >Three ways to define functions in JavaScript_javascript tips

Three ways to define functions in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:10:091076browse

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:

Copy code The code is as follows:

/*The first method is to use the function statement with the following format*/
function fn(){
alert("This is a function definition using the function statement");
}
fn();

/*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:

Copy code The code is as follows:

function Fn(){ //Define the constructor 
​this.elem="Here we use the function() constructor to define the function, haha";
this.fn = function(){  
alert("This is using the function() constructor to define a function, hehe");
}
}
var f = new Fn(); //Instantiation
alert(f.elem);
f.fn();
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn