There are two ways to define function expressions: function declaration and function expression.
The function is declared as follows:
function functionName(arg0,arg1,arg2){ //函数体 }
First is the function keyword, then the name of the function.
FF, Safrai, Chrome and Opera all define a non-standard name attribute for functions, through which the name specified by the function can be accessed. The value of this function is always equal to the identifier following the function keyword.
//只在FF,Safari,Chrome和Opera有效 alert(functionName.name)//functionName
The characteristic of function declaration is function declaration hoisting, which means that the function declaration is read before executing the code. This means that the function declaration can be placed after the statement that calls it.
sayHi(); function sayHi(){ alert("Hi!"); }
This example will not throw an error because the function declaration will be read before the code is executed.
The second type is function expression.
var functionName=function(arg0,arg0,arg2){ //函数体 }
This form looks like a regular variable assignment statement, that is, creating a function and assigning it to the variable functionName. The function created in this case is called an anonymous function because there is no identifier after the function keyword symbol. (Anonymous functions are sometimes also called lambda functions.) The name attribute of the anonymous function is an empty string.
Function expressions, like other expressions, must be assigned a value before use.
The following code will cause an error:
syaHi();//Uncaught ReferenceError: syaHi is not defined var sayHi=function(){ alert("Hi!"); }
Do not write code like the following. This is invalid syntax in ECMAScript. The JavaScript engine will try to correct the error, but different browsers will modify it differently.
//不要这样做 if(condition){ function sayHi(){ alert("Hi!"); } }else{ function sayHi(){ alert("Yo!"); } }
If you use function expressions, there will be no problem.
//可以这样做 var sayHi; if(condition){ sayHi=function(){ alert("Hi!"); } }else{ sayHi=function(){ alert("Yo!"); } }
You can create a function and assign it to a variable, and you can also return the function as the value of other functions.
function creatComparisonFunction(propertyName){ return function(object1,object2){ var value1=object1[propertyName]; var value2=object2[propertyName]; if(value1<value2){ return -1; }else if(value1>value2){ return 1; }else{ return 0; } }; }
creatComparisonFunction() returns an anonymous function. The returned function may be assigned to a variable or called in other ways; however, inside the creatComparisonFunction() function, it is anonymous. When treating the function as a value In any case, you can use anonymous functions.
7.1 Recursion
A recursive function is constructed when a function calls itself by name.
function factorial(num){ if(num<=1){ return 1; }else{ return num*factorial(num-1); } }
The above is a classic recursive factorial function. The following code may cause it to go wrong.
var anotherFactorial=factorial; factorial=null; alert(anotherFactorial(4));//Uncaught TypeError: factorial is not a function
The above code first saves the factorial() function in the variable anotherFactorial, and then sets the factorial variable to null. As a result, there is only one original reference left. When anotherFactorial() is called next, since factorial() must be executed, And factorial() is no longer a function, so it will cause an error.
In this case, using arguments.callee can solve the problem.
arguments.callee is a pointer to the function being executed, so it can be used to implement recursive calls to the function.
function factorial(num){ if(num<=1){ return 1; }else{ return num*arguments.callee(num-1); } }
When writing recursive functions, using arguments.callee is always safer than using function names, because it ensures that no matter how the function is called, there will be no problems.
But in strict mode, arguments.callee cannot be accessed through scripts.
However, you can use function expressions to achieve the same result.
var factorial=(function f(num){ if(num<=1){ return 1; }else{ return num*f(num-1); } }); console.log(factorial(4));//24
7.2 Closure
A closure is a function that has access to a variable in the scope of another function. A common way to create a closure is to create another function inside a function.
function creatComparisonFunction(propertyName){ return function(object1,object2){ var value1=object1[propertyName]; var value2=object2[propertyName]; if(value1<value2){ return -1; }else if(value1>value2){ return 1; }else{ return 0; } }; }
The two lines of code in bold are the code in the internal function (an anonymous function). These two lines of code access the variable propertyName in the external function. Even if the internal function is returned and called elsewhere , but it can still access the variable propertyName. The reason why it can still access this variable is because the scope chain of the internal function contains the scope of creatComparisonFunction().
When a function is called, an execution context and corresponding scope chain are created. Then, the activation object of the function is initialized using the values of arguments and other named parameters. But in In the scope chain, the active object of the external function is always in the second place, and the active object of the external function of the external function is in the third place... until the global execution environment as the end point of the scope chain.
During function execution, in order to read and write the value of a variable, you need to find the variable in the scope chain.
function compare(value1,value2){ if(value1<value2){ return -1; }else if(value1>value2){ return 1; }else{ return 0; } } var result=compare(5,10) console.log(result)//-1
以上代码先定义了compare()函数,然后又在全局作用域中调用了它.当调用compare()时,会创建一个包含arguments,value1,value2的活动对象.全局执行环境的变量对象(包含result和compare)在compare()执行环境的作用域链中则处于第二位
后台的每个执行环境都有一个表示变量的对象--变量对象.全局环境的变量对象始终存在,而像compare()函数这样的局部环境的变量对象,则只在函数执行的过程中存在.在创建compare()函数时,会创建一个预先包含全局变量对象的作用域链,这个作用域链被保存在内部的[[Scope]]属性中.当调用compare()函数时,会为函数创建一个执行环境,然后通过复制函数的[[Scope]]属性中的对象构建起执行环境的作用域链.此后,又有一个活动对象(在此作为变量对象使用)被创建并被推入执行环境作用域链的前端.
作用域链本质上是一个指向变量对象的指针列表,它只引用但不实际包含变量对象.
无论什么时候在函数中访问一个变量时,就会从作用域链中搜索具有相应名字的变量.一般来讲,当函数执行完毕后,局部活动对象就会被销毁,内存中仅保存全局作用域(全局执行环境的变量对象).但是,闭包的情况又有所不同.
在另一个函数内部定义的函数会将包含函数(即外部函数)的活动对象添加到它的作用域中.
var compare=creatComparisonFunction("name"); var result=comapre({name:"Nicholas"},{name:"Greg"});
下图展示了上面代码代码执行时,包含函数与内部匿名函数的作用域.
当createComparisonFunction()函数返回后,其执行环境的作用域会被销毁,但它的活动对象仍然会留在内存中;直到匿名函数被销毁后,createComparisonFunction()的活动对象都会被销毁.
//创建函数 var compare=creatComparisonFunction("name"); //调用函数 var result=comapre({name:"Nicholas"},{name:"Greg"}); //解除对匿名函数的引用(以便释放内存) compareNames=null;
通过将compareNames设置为等于null解除该函数的引用,就等于通知垃圾回收例程将其清除.随着匿名函数函数的作用域链被销毁,其他作用域(除了全局作用域)也都可以安全地销毁了.
由于闭包会携带包含它的函数的作用域,因此会比其他函数占用更多的内存.过度使用闭包可能会导致内存占用过多,慎重使用闭包.
7.2.1 闭包和变量
作用域链的这种配置的机制引出了一个值得注意的副作用,即闭包只能取得包含函数中任何变量的最后一个值.
闭包里所保存的是整个变量对象,而不是某个特殊的变量.
function createFunctions(){ var result=new Array(); for(var i=0;i<10;i++){ result[i]=function(){ return i; }; } return result; }
上面代码里这个函数会返回一个函数数组.表面上看,似乎每个函数都应该返回自己的索引值,但实际上,每个函数都返回10.因为每个函数的作用域链中都保存着createFunctions()函数的活动对象,所以它们引用的都是同一个变量i.当createFunction()函数返回后,变量i的值是10,此时每个函数都引用着保存变量i的同一个变量对象,所以在每个函数内部i的值都是10.
但是,我们可以通过创建另一个匿名函数强制让闭包的行为符合预期.
function createFunctions(){ var result=new Array(); for(var i=0;i<10;i++){ result[i]=function(num){ return function(){ return num; } }(i); } return result; }
重写之后,每个函数就会返回各自不同的索引值了.在这个版本中,我们没有直接把闭包赋值给数组,而是定义了一个匿名函数,并将立即执行匿名函数的结果赋给数组.这里的匿名函数有一个参数num,也就是最终的函数要返回的值.在调用每个匿名函数时,我们传入了变量i.由于函数参数是按值传递的,所以就会将变量i的当前值复制给参数num.而在这个匿名函数内部,又创建并返回了一个访问num的闭包.这个一来,result数组中的每个函数都有自己num变量的一个副本,因此就可以返回各自不同的数值了.
7.2.2 关于this对象
this对象是在运行时基本函数的执行环境绑定的:在全局函数中,this等于window,而当函数被作为某个对象的方法调用时,this等于那个对象.不过,匿名函数的执行环境具有全局性,因此其this对象通常指向window.
var name="the window"; var object={ name:"my object", getNameFunc:function(){ return function(){ return this.name; }; } }; alert(object.getNameFunc()());//the window(在非严格模式下)
每个函数在被调用时都会自动取得两个特殊变量:this和arguments.内部函数在搜索这两个变量时,只会搜索到其活动对象为止,因此永远不可能直接访问外部函数中的这两个变量.
不过,把外部作用域中的this对象保存在一个闭包能够访问到的变量里,就可以让闭包访问该对象了.
var name="the window"; var object={ name:"my object", getNameFunc:function(){ var that=this; return function(){ return that.name; }; } }; alert(object.getNameFunc()());//my object
在定义匿名函数之前,我们把this对象赋值给了一个名叫that的变量.而在定义了闭包之后,闭包也可以访问这个变量,因为它是我们在包含函数中特意声明的一个变量.即使在函数返回之后,that也仍然引用着object,所以调用object.getNameFunc()()就返回了my object.
注意:this和arguments也存在同样的问题.如果想访问作用域中的arguments对象,必须将对该对象的引用保存到另一个闭包能够访问的变量中.
var name="the window"; var object={ name:"my object", getName:function(){ return this.name; } }; console.log(object.getName());//my object console.log((object.getName)());//my object console.log((object.getName=object.getName)());//the window
最后一行代码先执行了一条赋值语句,然后再调用赋值后的结果.因为这个赋值表达式的值是函数本身,所以this的值不能得到维持,结果就返回了"this window".
7.2.3 内存泄露
由于IE9之前的版本对JScript对象和COM对象使用不同的垃圾收集例程,因此闭包在IE的这些版本中会导致一些特殊的问题.具体来说,如果闭包的作用域链中保存着一个HTML元素,那么就意味着该元素将无法被销毁.
function assignHandlet(){ var element=document.getElementById("someElement"); element.onclick=function(){ alert(element.id); }; }
以上代码创建了一个作为element元素事件处理程序的闭包,而这个闭包则又创建了一个循环引用.由于匿名函数保存了一个对assignHandler()的活动对象的引用,因此应付导致无法减少element的引用数.只要匿名函数存在,element的引用数至少也是1,因此它所占用的内存就永远不会被回收.不过这个问题可以通过稍微改写一下代码来解决.
function assignHandlet(){ var element=document.getElementById("someElement"); var id=element.id; element.onclick=function(){ alert(id); }; element=null; }
In the above code, the circular reference is eliminated by saving a copy of element.id in a variable and referencing the variable in the closure.
Script Home would like to remind everyone: the closure will reference the entire active object containing the function, which contains element. Even if the closure does not directly reference element, the active object containing the function will still save a reference. Therefore, there are It is necessary to set the element variable to null. In this way, the reference to the DOM object can be released, the number of references can be successfully reduced, and the memory occupied by it can be properly recycled.
Let me introduce function expressions to you.
In JavaScript programming, function expressions are a very useful technique. Using function expressions eliminates the need to name functions, thereby enabling dynamic programming. Anonymous functions, also known as lambda functions, are a powerful way to use JavaScript functions. The following summarizes the characteristics of function expressions.
Function expressions are different from function declarations. Function declarations require names, but function expressions do not. Function expressions without names are also called anonymous functions.
Recursive functions become more complicated when you are not sure how to reference the function; recursive functions should always use arguments.callee to call themselves recursively, and never use the function name - the function name may change.
A closure is created when other functions are defined inside a function. Closures have access to all variables inside the containing function, principle
as follows.
In the background execution environment, the closure's scope chain includes its own scope, the scope of the containing function, and the global scope. Normally, the scope of a function and all its variables are destroyed after the function execution ends.
However, when a function returns a closure, the scope of this function will be saved in memory until the closure no longer exists.
Using closures can imitate block-level scope in JavaScript (JavaScript itself has no concept of block-level scope). The key points are as follows.
Create and call a function immediately so that the code in it can be executed without leaving a reference to the function in memory.
The result is that all variables inside the function are destroyed immediately - unless some variables are assigned to variables in the containing scope (that is, the outer scope).
Closures can also be used to create private variables in objects. The related concepts and key points are as follows. Even though there is no formal concept of private object properties in JavaScript, closures can be used to implement public methods that provide access to variables defined in the containing scope.
Public methods that have access to private variables are called privileged methods.
You can use constructor mode and prototype mode to implement custom type privileged methods, and you can also use module mode and enhanced module mode to implement singleton privileged methods.
Function expressions and closures in JavaScript are extremely useful features, and you can use them to achieve many functions. However, because creating closures must maintain additional scope, overusing them can take up a lot of memory.