# JS函数表达式

## 递归

function factorial(num){
if(num<=1){
return 1;
}else{
return num*factorial(num-1);
}
}

var anotherFactorial = factorial;
factorial = null;

function factorial(num){
if(num<=1){
return 1;
}else{
return num*argument.callee(num-1);
}
}
//argument.callee是指向正在执行的函数的指针

function factorial(function f(num){
if(num<=1){
return 1;
}else{
return num*f(num-1);
}
});
//argument.callee是指向正在执行的函数的指针

## 闭包

function createComparisonFunction(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;
}
};
}

var value1 = object1[propertyName];
var value2 = object2[propertyName];

function compare(value1,value2){
if(value1<value2){
return -1;
}else if (value1>value2){
return 1;
}else{
return 0;
}
}
var result = compare(5,10);

var compare = createComparisonFunction("name");
var result = compare({name:"Nicholas"},{name:"Greg"});

//创建函数
var comapareNames = createComparisonFunction("name");
//调用函数
//var result = compareName({name:"Nicholas"},{name:"Greg"});
//解除对匿名函数的引用(以便释放内存)
compareNames = null;

#### 闭包与变量

function createFunctions(){
var result = new Array();
for (var i=0;i<10;i++){
result[i]=function(){
return i;
}
}
return result;
}

function createFunctions(){
var result = new Array();
for (var i=0;i<10;i++){
result[i]=function(num){
return function(){
return num;
};
}(i);
}
return result;
}

#### 关于this对象

this对象时在运行时基于函数的执行环境绑定的，匿名函数的执行环境具有全局性，因此对象通常指向windows。

var name = "The window";
var object = {
name : "MyObject",
getNameFunc : function(){
return function(){
return this.name;
};
}
}

var name = "The window";
var object = {
name : "MyObject",
getNameFunc : function(){
var that =this;
return function(){
return that.name;
};
}
}

var name = "The window";
var object = {
name : "MyObject",
getName ：function(){
return that.name;
}
}；

object.getName();   //"My Object"
(bject.getName)();   //My Object"
object.getName和(bject.getName)的定义相同
(object.getName() = object.getName)(); //"The windows"在非严格模式下

#### 内存泄漏

function assignHandler(){
var element = document.getElementById("someElement");
element.onclick = function(){
}
}

function assignHandler(){
var element = document.getElementById("someElement");
var id = element.id;
element.onclick = function(){