Three ways to define a function in JavaScript

  • 2020-05-16 06:18:05
  • OfStack

In the world of JavaScript, there are many ways to define functions, which is exactly the point of JavaScript's flexibility, but it is precisely this that makes it confusing for beginners, especially those with no language background. Just as the so-called all roads lead to Rome, but if there are too many roads, it will make travelers at a loss, because they don't know which road is the right one to take.


/* The first 1 This way, use function Statement in the following format */
function fn(){
  alert(" This is to use function The statement defines the function ");
}
fn(); /* The first 2 This way, use Function() The constructor clones the function */
var F = new Function("a","b","alert(a+b)");
F(a,b); It is equivalent to the following code:
function F(a,b){
  alert(a+b);
} /* The first 3 The way to do it is to use a function of a direct quantity */
var zhenn = function(){
  alert("zhenn");
}
zhenn();

Among them, the methods of using "function statement" and "function direct quantity" to define functions seem to be common and easy to understand, so I will not say more here. For the use of the Function() constructor kroon function, 1 is rarely used because a function usually consists of multiple statements, which, if passed as a string as a parameter, will inevitably make the code unreadable.

And I'm going to mention the one constructor here, which literally looks like a function, but it's not a function, it's just a model of a function. For example, the constructor is the equivalent of a newly assembled car, which, when viewed from a distance or close up, is a car that has not been refueled (representing a necessary step before use), so it does not start. If you want the car to run properly, you have to oil it, which is equivalent to instantiating the constructor, otherwise it won't work! Here's an example:


function Fn(){    // Define the constructor
  this.elem =" So this is using function() The constructor defines the function, hehe ";  
  this.fn = function(){    
    alert(" This is to use function() The constructor defines the function, heh heh ");  
  }
}
var f = new Fn();  // instantiation
alert(f.elem);
f.fn();


Related articles: