liuqinh2s' blog

Do something cool!

扁平数组嵌套化(flat to nest)

  1. 菜单数组转换为嵌套树形结构,但示例只有两级
1
2
3
4
5
6
7
8
9
10
11
12
[
{ id: 1, menu: '水果', level: 1 },
{ id: 2, menu: '橘子', level: 2, parentId: 1 }
// ...
]
// 转换为
[
{
id: 1, menu: '水果', level: 1, children: [{ id: 2, menu: '橘子', level: 2, parentId: 1 }]
},
// ...
]

以下是我给出的解答,未经过严格测试

阅读全文 »

执行上下文中有个作用域链,当查找一个变量时会顺着这个链找。

函数的作用域在函数定义的时候就决定了。这是因为函数对象有个内部属性[[scope]]

函数的生命周期分为:函数创建函数调用

函数创建的时候,会把其所处执行上下文的作用域链直接赋值给函数的内部属性[[scope]](这就是词法作用域的原理了),函数调用的时候会创建自己的执行上下文,并把自己的AO[[scope]]合并成新的作用域链:

假设要实现动态作用域的话,[[scope]]就得在调用时去执行上下文栈的上一帧去取。

1
Scope = [AO].concat([[scope]]);
阅读全文 »

闭包是干什么用的

本质上闭包就是为了拓展查找自由变量的范围

MDN 对闭包的定义为:

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment)

一个函数和对其周围状态(lexical environment,词法环境)的引用捆绑在一起(或者说函数被引用包围),这样的组合就是闭包(closure)。

1
2
3
4
5
6
7
8
9
function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() {
// displayName() is the inner function, a closure
console.log(name); // use variable declared in the parent function
}
displayName();
}
init();

name 是 displayName 函数所处环境中的变量,它们一起构成了闭包。而闭包的实现依赖于执行上下文中的作用域链。

上面这个例子有点平平无奇了,让我们看一个神奇一点的例子:

阅读全文 »

执行上下文中包含哪些东西

对于每个执行上下文,都有三个重要属性:

  • 变量对象(Variable object,VO)
  • 作用域链(Scope chain)
  • this

本篇就来讲讲第一个变量对象

阅读全文 »
0%