English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
There are generally three ways to define a function in Javascript:
Function keyword (function) statement:
function fnMethodName(x){alert(x);}
Function literal (Function Literals):
var fnMethodName = function(x){alert(x);}
Function constructor Function():
var fnMethodName = new Function('x','alert(x);') // The number of parameters of the Function constructor is variable. The last parameter writes the function body, and the preceding parameters write the parameters.
The above three methods define the same method function fnMethodName, the1One of which is the most commonly used method, and the latter two are to copy a function to a variable fnMethodName, which is an anonymous function.
Execution order of the function:
Example1.
test1(); function test1() { //Function declaration alert("1111"); } test2(); var test2 = function(){ //Function literal alert("2222"); } test3(); var test3 = new Function("alert(3333);); //at runtime, initializes the function body
Execution result: Pop-up1111but no pop-up222, 3333
Principle: Pop-up1111 because JS function declaration is hoisted
No pop-up2222, 3333because the function literal is not a function declaration, the function literal represents a method that is parsed at runtime, in calling test2The function body of the function literal is not declared before ()
Example2.
function f(){return 1;} console.log(f()); // The fourth function overrides the first function var f = new Function("return 2; console.log(f()); // The second function overrides the fourth function var f = function() {return 3;} console.log(f()); // The third function overrides the second function function f(){return 4;} console.log(f()); // The fourth function has been overridden var f = new Function("return 5; console.log(f()); // The fifth function overrides the third function var f = function(){return 6;} console.log(f()); // The sixth function overrides the fifth function
Execution result: 4 2 3 3 5 6
Principle: First find the function declaration,4Function declaration overrides1So the result of the first f() is4 .
Function scope:
var k = 4; window.onload=function() { var k=1; function t1() { var k = 2; function test() {return k;} console.info(test()); // popup 2 var test = function() {return k;}; console.info(test()); // popup 2 var test = new Function("return k;"); // Dynamically new each time, top-level scope, unable to access local variables console.info(test()); // popup 4 } t1(); });
II. Differences between function literals and Function() constructor
Although function literals are anonymous functions, the syntax allows specifying any function name for them. When writing recursive functions, it is possible to call them themselves, but this is not possible using the Function() constructor.
var f = function fact(x) { if (x < = 1) return 1; else return x*fact(x-1); });
The Function() constructor allows JavaScript code to be dynamically created and compiled at runtime. In this way, it is similar to the global function eval().
The Function() constructor parses the function body and creates a new function object each time it is executed. Therefore, calling the Function() constructor within a loop or a frequently executed function is very inefficient. In contrast, function literals are not recompiled every time they are encountered.
When creating a function using the Function() constructor, it does not follow the typical scope, treating it as a top-level function all the time.
var y = 'global'; function constructFunction() { var y = 'local'; return new Function('return y'); // Unable to access local variables } alert(constructFunction()()); // Output 'global'
Function literal:
As long as it is expression syntax, the script host considers function to be a literal function. If nothing is added, and it starts with function alone, it is considered a function declaration. Placing function inside an expression, such as arithmetic operations, the host will also treat it as a literal, as follows:
var a = 10 + function() { return 5; })();
Exaggerate a bit, as follows:
(function(){ alert(1); } ) ( ); ( function() { alert(2); } ( ) ); void function() { alert(3); }(); 0, function() { alert(4); })(); -function() { alert(5); })(); +function() { alert(6); })(); !function() { alert(7); })(); function() { alert(8); })(); typeof function() { alert(9); })();
There are many ways to define functions in JavaScript, and function literals are one of them. For example, var fun = function(){}, if the 'function' is not assigned to 'fun', it is an anonymous function.
Well, let's see how anonymous functions are called.
1, function call that gets the return value after execution
//Method one, call the function, get the return value. Force the operator to make the function call execute (function(x,y){ alert(x+y); return x+y; }3,4)) //Method two, call the function, get the return value. Force the function literal to execute and return a reference, which is then called to execute (function(x,y){ alert(x+y); return x+y; })(3,4);
2, ignore the return value after execution
//Method three, call the function, ignore the return value void function(x) { x = x-1; alert(x); }9);
Well, let's take a look at the incorrect calling method
//Incorrect calling method function(x,y){ alert(x+y); return x+y; }3,4);
III. Some explanations on application examples
Object literal creates an object:
var obj = {x:[1,2],y:23});
The code is the same as below.
var obj=new Object(); obj.x=new Array(1,2); obj.y=23;
Test:
for(var i in obj) alert(obj[i]);
Function literal: it is an expression rather than a statement.
(function(){}())
As shown in the following example:
(function(){ document.write(“some script code”); })() var a=(function(s){return s})(“abc”); alert(a); var b=function(s){return s}; alert(b(“abc”));
How to explain this
You should remember this writing style
var a=function (){}
Then how to run 'a', it is 'a()'
The same principle, if we do not use the variable 'a' to store it, how to write it is
function(){}()
But you will find that this is wrong
Because the parser parses when it finds that the end of the function is reached with the '}'
It does not treat that function as a block to run
Then adding parentheses is to force the function block to be treated as a block
Four methods of JS function calling:Method calling mode, function calling mode, constructor calling mode, apply, call calling mode
1.Method invocation mode:
First define an object, then define methods in the properties of the object, and execute the method through myobject.property, this refers to the current myobject object.
var blogInfo={ blogId:123, blogName: "werwr", showBlog: function(){alert(this.blogId);} }); blogInfo.showBlog();
2.Function invocation mode
Define a function, set a variable name to save the function, at this time, this points to the window object.
var myfunc = function(a,b){ return a+b; } alert(myfunc(3,4))
3.Constructor invocation mode
Define a function object, define properties in the object, and define methods in the prototype object. When using the methods of prototype, the object must be instantiated to call the method.
var myfunc = function(a){ this.a = a; }); myfunc.prototype = { show: function(){alert(this.a);} } var newfunc = new myfunc("123123123"); newfunc.show();
4.apply, call invocation mode
var myobject={}; var sum = function(a,b){ return a+b; }); var sum2 = sum.call(myobject,10,30); //var sum2 = sum.apply(myobject,[10,30]); alert(sum2);
This brief discussion of the three ways to define js functions & four ways to call them & the order of calling is all the content that the editor shares with everyone. I hope it can provide a reference for everyone, and I also hope everyone will support and cheer for the tutorial.