当前位置 : 主页 > 网络编程 > JavaScript >

jquery闭包

来源:互联网 收集:自由互联 发布时间:2021-06-28
gistfile1.txt /*** 闭包*/function outter(){var m = 100;var n = 1;return function(){return m;}}function outter1(age){var m = 3;return{name:m,age:age};}var o = outter1(20);var o = outter1(30);console.log(o.name);//避免内存泄露的方法
gistfile1.txt
/**
* 闭包
*/
function outter(){
	var m = 100;
	var n = 1;
	return function(){
		return m;
	}
}
function outter1(age){
	var m = 3;
	return{name:m,age:age};
}
var o = outter1(20);
var o = outter1(30);
console.log(o.name);



//避免内存泄露的方法    new WeakSet.add(outter());   
var c = outter();
var x = c();
console.log(x);



/*
闭包计数器
*/

function counter(m){
	return function(){
		return ++m;
	}
}
var c1 = counter(0);
var c2 = counter(3);
for(var i=0;i<10;i++){
	console.log("c1..."+c1());
	console.log("c2..."+c2());
}



/*
比较器
*/
var  o1={id:2,name:"evan"};
var  o2={id:8,name:"alice"};
var  o3={id:1,name:"eric"};
function createCompareisionFactory(propertyName){
	return function(o1,o2){
		return o1[propertyName]>o2[propertyName]?1:o1[propertyName]==o2[propertyName]?0:-1;
	}
}
var idComparator = createCompareisionFactory("id");
var nameComparator = createCompareisionFactory("name");

var m = idComparator(o1,o2);
var m1 = nameComparator(o1,o2);
console.log(m1);

var os = [o1,o2,o3];
os.sort(idComparator);
console.log(os);





/*
陷阱	
*/
//陷阱写法 输出所有都是10
// function fnFactory(){
// var fns=[];
// for (var i = 0; i < 10; i++) {
// fns[i]=function(){return i;}
// }
// return fns;
// }

//输出1到10
function fnFactory(){
	var fns = [];
	for(var i=0;i<10;i++){
		fns[i] = function(x){

			return function(){
				return x;
			}
		}(i);
	}
	return fns;
}

var fs = fnFactory();
for(var i=0;i
网友评论