闭包:
def:函数内部定义的子函数用到了父函数内部的变量,形成的特定作用域
功能:
1.保存函数的执行状态
code:
‘a1c2f3g4’中的数字依次用[‘b’.’d’,’e’,’h’]替换
//count变量会保存在闭包作用域内,表示func被调用的次数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Closure1</title>
</head>
<body>
<script type="text/javascript">
var arr = ['b','d','e','h'];
var str = 'a1c2f3g4';
var func = (function() {
var count = 0;
return function() {
return arr[count++];
}
})();
str = str.replace(/\d/g, func);
console.log(str);
// abcdfegh
//不使用闭包
function sum(i, j) {
var add = function (i, j) {
return i+j;
}
return add(i, j);
}
var startTime = new Date();
for(var i=0;i<1000000;i++) {
sum(1, 1);
}
var endTime = new Date();
console.log(endTime-startTime)
//49
//使用闭包
var sum = (function () {
var add = function(i, j){
return i+j;
}
return function(i,j){
add(i,j);
}
})()
var startTime = new Date();
for(var i=0;i<1000000;i++) {
sum(1, 1);
}
var endTime = new Date();
console.log(endTime-startTime)
//4
</script>
</body>
</html>
2.封装
私有变量,不被外部调用
3.性能优化
由于作用域的范围,节约了执行时间
first-class function(函数即变量):
功能如下:
1.函数可以当做参数
异步回调函数例如ajax
2.函数作为返回值
①Function.prototype.bind()此方法与function.apply(obj,param)方法类似
是指先绑定不作操作,如若执行则需要Function.prototype.bind()()
返回的是函数引用不是函数值
code:
var move = function (x,y) {
this.x += x;
this.y += y;
};
var p = {x:1,y:1};
var pmove = move.bind(p,2,2);
console.log(p)
// Object {x: 1, y: 1}
pmove();
console.log(p)
// Object {x: 3, y: 3}
②curry柯里化