//闭包
function createComparisonFunction(propertyName){
var tes = 4 ;
return function(object1,object2){
var value1 = object1[propertyName];
var value2 = object2[propertyName];
//alert(value1)
if(value1 < value2){
alert('1')
}else if(value1 < value2){
alert('2')
}else{
alert('3');
return tes;
}
}
}
var compareNames = createComparisonFunction("name");
var result = compareNames({name:"nick"},{name:"cook"});
//compareNames = null;
console.log(result)
//闭包与变量 javascript高级程序设计第181
/*function test(){
var result = new Array();
for(var i = 0; i<10; i++){
result[i] = function(){
return i;
}
}
return result;
}
//alert(test() instanceof Array); //true
alert(test()2); //10 2替换为0·~9,值都为10*/
/*function test(){
var result = new Array();
for(var i = 0; i<10; i++){
result[i] = function(num){
return function(){
return num;
}
}(i)
}
return result;
}
//alert(test() instanceof Array); //true
alert(test()2); //2 2替换为i,值为i*/
/*
闭包中的this
闭包下的this对象
var name = "the window";
var object = {
name:"gejin",
getNamefunction:function(){ //匿名函数1
alert(this.name) //gejin
return function(){ //匿名函数2
alert(this.name) //the window 原因:object.getNamefunction()();调用匿名函数2时,2函数会自动取得this和arguments两个特殊变量,
//2内部函数在搜索这两个变量时,只会搜索到其活动对象(我的理解是包括函数内部的变量和arguments),不能直接访问外部函数1的this和arguments
//所以这里的this是window
return this.name;
}
}
}
object.getNamefunction()();*/
/var name = "the window";
var object = {
name:"gejin",
getNamefunction:function(){ //匿名函数1
alert(this.name) //gejin
var that = this;
return function(){ //匿名函数2
alert(that.name); //gejin
return that.name;
}
}
}
object.getNamefunction()();/
var name = "the window";
var object = {
name:"gejin",
getName:function(){
return this.name;
}
}
alert(object.getName()); //gejin
(object.getName)(); //gejin
(object.getName = object.getName)(); //the window 这是一个赋值语句,赋值语句的返回值是等号右边的值,即(object.getName = object.getName)的返回值是object.getName
//所以(object.getName = object.getName)的返回值就是object.getName指向的函数本身了,即function(){return this.name;}
//所以(object.getName = object.getName)();等于function(){return this.name;}(),此段代码的调用者为 window, 所以 this 指向 window。