批改状态:合格
老师批语:闭包理解了, js原理就理解了一半,这也是面试最常问到的问题
- 实例演示变量与常量的区别;
- 函数与匿名函数的区别
- 箭头函数的参数特征
- 闭包原理与实现并演示它
- 四种高阶函数,全部实例演示,并理解回调和纯函数是什么,写出你的答案
// 变量let a;// 未初始化变量,输出 undefinedconsole.log(a);// 变量赋值a = 0;// 输出 0console.log(a);// 变量更新a = 1;// 输出 1console.log(a);// 初始化时赋值let b = 2;// 输出 2console.log(b);// 常量const c = 3;// 输出 3console.log(c);

// 函数function sum1(a, b) {return a + b;}// 函数输出 1 + 2 输出 3console.log(sum1(1, 2));// 匿名函数const sum2 = function(a, b) {return a + b;}// 匿名函数 2 + 3 输出 5console.log(sum2(2, 3));

// 没有参数时,参数 () 不能省略let sum = () => true;// 返回 trueconsole.log(sum());// 只有一个参数时,参数 () 可以省略sum = (a) => a;sum = a => a;// 返回 0console.log(sum(0));// 两个或多个参数,参数 () 不能省sum = (a, b) => a + b;// 返回 3;console.log(sum(1, 2));// 多条语句时,函数体 {} 不能省sum = (a, b) => {let c = a + b;return c;}// 返回 5console.log(sum(2, 3));

let x = 1;// 函数 y 内访问自由变量 x,函数 y 是闭包函数let y = () => x;// 返回 1console.log(y());// 函数 s 内访问自由变量 x ,函数 s 是闭包函数let s = () => {// 变量 y 对函数 s 是私有变量let y = x + 1;// 变量 y 对函数 z 是自由变量,函数 z 也是闭包函数let z = () => x + y;return z;}// 返回 3console.log(s()());

高阶函数: 使用函数为参数或者将函数做为返回值的函数
// 回调函数let fa = a => a();let foo = () => 'foo';// 把函数 foo 作为参数传递给函数 fa,foo 是回调函数console.log(fa(foo));
// 偏函数:简化声明fa = (a, b) => {return c => a + b + c;}// 返回 6console.log(fa(1, 2)(3));
// 柯里化:简化调用参数fa = a => b => c => a + b + c;// 返回 9console.log(fa(2)(3)(4));
// 纯函数fa = a => a;console.log(fa(true));

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号