闭包

⼀个函数和对其周围状态(lexical environment,词法环境)的引⽤捆绑在⼀起(或者说函数被引⽤

包围),这样的组合就是闭包(closure)

也就是说,闭包让你可以在⼀个内层函数中访问到其外层函数的作⽤域

1
2
3
4
5
6
7
8
function init() {
var name = "Mozilla"; // name 是⼀个被 init 创建的局部变量
function displayName() { // displayName() 是内部函数,⼀个闭包
alert(name); // 使⽤了⽗函数中声明的变量
}
displayName();
}
init();

任何闭包的使⽤场景都离不开这两点:

创建私有变量

延⻓变量的⽣命周期

⼀般函数的词法环境在函数返回后就被销毁,但是闭包会保存对创建时所在词法环境的引⽤,即便

建时所在的执⾏上下⽂被销毁,但创建时所在词法环境依然存在,以达到延⻓变量的⽣命周期的⽬的

例如计数器、延迟调⽤、回调等闭包的应⽤,其核⼼思想还是创建私有变量和延⻓变量的⽣命周期

Javascript中如何实现函数缓存

函数缓存,就是将函数运算过的结果进⾏缓存

本质上就是⽤空间(缓存存储)换时间(计算过程)

常⽤于缓存数据计算结果和缓存对象

实现函数缓存主要依靠闭包、柯⾥化、⾼阶函数

JavaScript字符串的常⽤⽅法有哪些?

concat⽤于将⼀个或多个字符串拼接成⼀个新字符串

这⾥的删的意思并不是说删除原字符串的内容,⽽是创建字符串的⼀个副本,再进⾏操作

常⻅的有:

slice()

substr()

substring()

1
2
3
4
5
6
7
let stringValue = "hello world";
console.log(stringValue.slice(3)); // "lo world"
console.log(stringValue.substring(3)); // "lo world"
console.log(stringValue.substr(3)); // "lo world"
console.log(stringValue.slice(3, 7)); // "lo w"
console.log(stringValue.substring(3,7)); // "lo w"
console.log(stringValue.substr(3, 7)); // "lo worl

这⾥改的意思也不是改变原字符串,⽽是创建字符串的⼀个副本,再进⾏操作

常⻅的有:

trim()、trimLeft()、trimRight()

删除前、后或前后所有空格符,再返回新的字符串

1
2
3
4
let stringValue = " hello world ";
let trimmedStringValue = stringValue.trim();
console.log(stringValue); // " hello world "
console.log(trimmedStringValue); // "hello world

repeat()

padStart()、padEnd()

toLowerCase()、 toUpperCase()