Function 函数式编程
函数是一等公民
- 函数可以作为参数传递
- 函数可以作为返回值
- 函数可以作为变量赋值
- 一等公民指的是函数与其他数据类型一样,处于平等地位,能参与运算,也可以作为参数传递,赋值等。
- 代码优化案例
// 优化前
let functionInvoke = {
index(posts) {
return views.index(posts);
},
show(pic) {
return views.show(pic);
},
};
// 优化后
let functionInvoke = {
index: views.index,
show: views.show,
};
高阶函数
- 接受一个或者多个函数作为其入参
- 返回值是一个函数
- 两者满足其一,则为高阶函数
- 使用高阶函数的意义
- 抽象可以帮我们屏蔽一些细节,只需要关注目标
- 高阶函数是用来抽象通用的问题
- 函数作为参数
案例
模拟常用的高阶函数
// 模拟常用高阶函数 (函数作为参数)
function filter(arr, fn) {
let results = [];
for (let i = 0; i < arr.length; i++) {
if (fn(arr[i])) {
results.push(arr[i]);
}
}
return results;
}
console.log(filter([1, 2, 3, 4], (item) => item % 2 === 0)); // [2,4]
function map(arr, fn) {
let results = [];
for (let value of arr) {
results.push(fn(value));
}
return results;
}
console.log(map([2, 3, 4, 5, 6, 7], (item) => item * 2)); // [ 4, 6, 8, 10, 12, 14 ]
function every(arr, fn) {
let result = true;
for (let value of arr) {
result = fn(value);
if (fn(value) === false) break;
}
return result;
}
console.log(every([5, 6, 7, 8], (num) => num >= 4)); // true
console.log(every([5, 6, 7, 8], (num) => num > 5)); // false
- 函数作为返回值
案例
基础案例理解
// 函数作为返回值
function makeFn() {
let msg = "world";
return function () {
console.log("hello" + msg);
};
}
let fn = makeFn();
fn(); // helloworld
封装 once 函数, 使其只能被调用一次
function once(fn) {
let done = false;
return function () {
if (!done) {
done = true;
fn.apply(this, arguments);
}
};
}
let pay = once(function (money) {
console.log(`请支付${money}元.`);
});
pay(66); // 请支付66元.
pay(88); // '不执行 !!!'
闭包
传统概念:
闭包: 函数和其周围状态的引用捆绑在一起,形成闭包
通俗来讲:
一个可以访问另一个函数内部变量的函数就叫做闭包
(一个函数可以访问另一个函数内部的变量,这就叫闭包)- 比如: 函数 b 可以访问 函数 a 内部的变量,即 函数 b 就是 函数 a 的闭包.
案例解释:
makePower2TF
函数可以访问到makePowerTransform
函数中的变量,所以形成闭包
// 求指数
console.log(Math.pow(2, 3)); // 8
console.log(Math.pow(3, 3)); // 27
console.log(Math.pow(4, 3)); // 64
console.log(Math.pow(4, 2)); // 16
function makePower2(num) {
return Math.pow(num, 2);
}
function makePower3(num) {
return Math.pow(num, 3);
}
function makePower4(num) {
return Math.pow(num, 4);
}
console.log(makePower2(2)); // 4
console.log(makePower3(2)); // 8
console.log(makePower4(2)); // 16
// 函数改造
function makePowerTransform(power) {
return function (num) {
return Math.pow(num, power);
};
}
// 将指数固定 ,得到返回的函数,最后求幂
let makePower2TF = makePowerTransform(2);
let makePower3TF = makePowerTransform(3);
console.log(makePower2TF(2)); // 4
console.log(makePower2TF(3)); // 9
console.log(makePower2TF(4)); // 16
console.log(makePower3TF(4)); // 64