js链表的理解

      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查找的时候非父级作用域的变量可以读取吗?

阅读 2.5k
1 个回答

所有的项都存在head中,也就是LinkedList这个闭包中

clipboard.png

此处验证也比较简单,我们在chrome的调试工具中打断点,可以看到是在闭包中的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题