Home > Article > Web Front-end > Detailed analysis of JavaScript function definition_javascript skills
Function
A few key points:
a). Functions are first-class citizens in JavaScript (importance)
.
c). The function defines an independent variable scope
Definition method
Named functions are global unless defined inside another function.
// 全局的命名函数 function add(x, y) { return x + y; } console.info(add(100, 200)); //300
Anonymous functions are usually assigned to a variable and then called through the variable.
var func = function (x, y) { return x + y; } console.info(func(5, 2)); //7
console.info( function (x, y) { return x + y; }(100, 200) //立即调用 );
The named function can be used first and then defined
console.info(sum(10, 10)); function sum(num1, num2) { return num1 + num2; }
//console.info(sumFunc(10, 10)); //Uncaught TypeError: Property 'sumFunc' of object [object Object] is not a function var sumFunc = function (num1, num2) { return num1 + num2; }; console.info(sumFunc(10, 10));
Function return value:
function func() { } console.info(func()); //undefined function func2() { return; //空的返回语句 } console.info(func2()); //undefined
The pit hidden in the return:
var func = function (x, y) { var sum = x + y; return { value : sum } }
However:
var func = function (x, y) { var sum = x + y; return { value: sum }; } console.info(func(5,5)); //undefined
Calling func(5,5) displays undefined
The editor added a semicolon after the return for us; however, it is of no use in this case.
Functions are objects:
function add(x, y) { return x + y; } console.info(add(100, 200)); //300 var other = add; //other和add引用同一函数对象 console.info(other(300, 400)); //700 console.info(typeof other); //function console.info(add === other); //true
Nested defined functions:
function outerFunc(a, b) { function innerFunc(x) { return x * x; } return Math.sqrt(innerFunc(a) + innerFunc(b)); } console.info(outerFunc(3, 4)); //5
Access external variables:
var globalStr = 'globalStr'; function outerFunc2(argu) { var localVar = 100; function innerFunc2() { localVar++; console.info(argu + ":" + localVar + ":" + globalStr); } innerFunc2(); //hello:101:globalStr } outerFunc2("hello");
Function that returns a function:
function outerFunc(x) { var y = 100; return function innerFunc() { console.info(x + y); } } outerFunc(10)(); //110