在函数外部能够访问函数内部的函数 叫作闭包 闭包的优缺点不一一赘述
首先实现一个简单闭包 传入一个参数
function add(x){
var count = x
function bdd(){
return count += 1
}
return bdd() //返回一个函数
}
var result = add(0)
console.log(result) //打印一个函数
console.log(result()) //打印1
console.log(result()) //打印2
console.log(result()) //打印3
传入两个参数
function add(x) {
var count = x
function bdd(y) {
count += y
return count
}
return bdd
}
var result = add(0)
console.log(result) //bdd()
console.log(result(1)) //1
console.log(result(2)) //3
console.log(result(3)) //6
//此时可以链式调用两次
/*
var result = add(1)(2)
console.log(result) //3
*/
传入三个参数
function add(x) {
var count = x;
function bdd(y) {
count += y
return cdd
}
function cdd(z) {
return count += z
}
return bdd
}
var bb = add(1)(2)(3)
console.log(bb) //6
最近写了一道函数柯里化的原声题目,可以修改为
function add(x){
var sum = x;
var tmp = function(y){
sum = sum + y;
return tmp;
};
// 直接使用toString()会转为字符串;
// toString(2) 会转为2进制(8、16进制同理)
// 判断类型
// Object.prototype.toString.call([]) "object Array]"
// Object.prototype.toString.call({}) "[object Object]"
tmp.toString = function(){
return sum;
};
return tmp;
}
var result = add(1)(2)(3)(4);
alert(result);