<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Application of function expressions</title>
</head>
<body>
<script type="text/javascript">
// 1. Declarative (variables will be promoted, you can use them first and then assign values)
function functionName1(arg0,arg1,arg2){ // Function body } // Access the function name through the name attribute: only in Firefox, Safari, Chrome, Opera Effective console.log(functionName1.name)// functionName1 // 2. Function expression (need to be defined before use) //2.1 Create a function and then assign it to a variable var functionName2 = function(arg0,arg1,arg2){ // Function Body }
console.log(functionName2.name)// "" (an anonymous function returns an empty string)
// Considering that variable promotion will bring unexpected results in js programs, it is recommended to use function expressions in conditional statements
var sayHi;
var condition=true;
if(condition){
sayHi = function(){ alert("Hi!") } }else{ sayHi = function(){ alert('No') } } // 2.2 Use functions as the value of other functions Return (sort objects) function createCompareFunction(propertyName){ return function(obj1,obj2){ var val1 = obj1[propertyName];
var val2 = obj2[propertyName];
if(val1<val2){
return -1
}else if(val1>val2){
return 1
}else{
return 0;
}
}
}
//3. Function expression optimization recursion
//1. Classical factorial
function factorial(num){
if(num<=1){ return 1 }else{ return num*factorial(num-1) } } //The disadvantages are as follows var anotherFacorial=factorial; factorial = null; console.log(anotherFacorial(6));//Error! ! ! "Uncaught TypeError: object is not a function" // argments.callee is a pointer to the function being executed (commonly speaking: instead of the function name), which can solve this problem and implement recursive calls to functions function factorial(num){ if( num<=1){ return 1 }else{ return num*arguments.callee(num-1) }
}
var anotherFacorial=factorial;
factorial = null;
console.log(anotherFacorial(6)) // 720
// Arguments.callee cannot be accessed in strict mode, so function expressions can be used to solve
var factorial = (function f(num ){ if(num<=1){ return 1 }else{ return num.f(num-1) } })
//4. About this object
var name = 'window';
var obj = { name:'obj', getNameFunc:function(){ var that = this; return function(){ return that.name; } } } console. log(obj.getNameFunc()());// 'obj' // This will change var name2 = 'window2'; var obj2 = { name2:'obj2', getName:function(){ return this. name2; } } console.log(obj2.getName());//obj2
console.log((obj2.getName)());//obj2
console.log((obj2.getName=obj2.getName)());//window2
</script>
</body>
</html>