function LinkedList() {
let Node = function (ele) {
this.ele = ele
this.next = null
},
length = 0, head = null;
this.append = function (ele) {
var node = new Node(ele), //{1}
current; //{2}
if (head === null) { //列表中第一个节点 //{3}
head = node;
} else {
current = head; //{4}
//循环列表,直到找到最后一项
while (current.next) {
current = current.next;
}
//找到最后一项,将其next赋为node,建立链接
current.next = node; //{5}
}
length++; //更新列表的长度 //{6}
};
this.print = function () {
var current = head, //{1}
string = ''; //{2}
while (current) { //{3}
string += current.ele; //{4}
current = current.next; //{5}
}
return string; //{6}
};
}
let LinkedList1= new LinkedList();
[1,2,3,4,5,6].forEach(function (value) {
LinkedList1.append(value)
})
console.log(LinkedList1.print(); //123456
这样实现一个链表的话,每一个项存在哪个函数的作用域?如果是append这个函数的作用域,print查找的时候非父级作用域的变量可以读取吗?
所有的项都存在head中,也就是LinkedList这个闭包中
此处验证也比较简单,我们在chrome的调试工具中打断点,可以看到是在闭包中的