In the JavaScript world, there are a variety of ways to define a function, which is the embodiment of javascript flexibility, but it is the reason for beginners to be confused, especially for students without language basis. Is the so-called road to Rome, but if too many roads, will let the road people at a loss, because do not know to go that road is the right way, oh, a big piece of nonsense, gossip less, first look at the code:
Copy Code code as follows:
/* The first method, using the function statement, the format is as follows * *
function fn () {
Alert ("This is a function definition with a function statement");
}
FN ();
/* The second method, using the function () constructor to clone the function * *
var F = new Function ("A", "B", "Alert (a+b)");
F (A,B);
It actually corresponds to the following code:
function F (a,b) {
alert (A+B);
}
/* The third method, using the direct amount of the function * *
var Zhenn = function () {
Alert ("Zhenn");
}
Zhenn ();
The use of "function statements" and the use of "direct volume of functions" to define the function of the method seems to be more common, but also better to understand, not much to say. Cloning a function with a function () constructor is rarely used because a function usually has more than one statement, and if you pass them as a string, it will inevitably make the code less readable.
To mention the constructor here, in fact, literally, the constructor seems to be a function, but it's not a function, it's just a function model. As an improper example, the constructor is the equivalent of a newly assembled car, which is a car, either far or near, but it is not refueling (represents a necessary step before use), so it does not start. If you want this car to travel normally, you must add oil to it, in fact, this process is equivalent to the instantiation of the constructor, otherwise it will not function properly! Look at the following example:
Copy Code code as follows:
function Fn () {//define Constructor
This.elem = "Here is to use function () constructor to define functions, hehe";
This.fn = function () {
Alert ("This is the use function () constructor to define the functions, hehe");
}
}
var f = new Fn (); Instantiation of
alert (F.elem);
F.fn ();