JS-仿写DOM节点

289 阅读1分钟

本篇章代码部分主要实现了链表的操作,包括增加子节点,关联子节点为兄弟节点,删除子节点,查找第一个子元素和最后一个子元素,查看当前节点在父节点中的位置

目的:用于练习原型链编程,解构,数组方法,存储描述符,加深对DOM属性的记忆

代码没有视图部分,直接运行即可 代码

//增加子节点,并关联兄弟节点
MyNode.prototype.appendChild = function(node) {
    if(this.children.length>0){//判断是否在添加第一个节点,不是
        node.preSbing = this.children[this.children.length - 1]
        this.children[this.children.length - 1].nextSbing = node
    }else{//是
        node.preSbing = null
    }
    this.children.push(node)
    node.nextSbing = null
}
//删除子节点,并重新关联兄弟节点
MyNode.prototype.deletChild = function(node) {
    if(this.children.length==0){//没有节点删除毛线
        return;
    }
    var childIndex = this.children.indexOf(node)//查看要删除的节点在数组中的位置,即获取数组下标
    //断开链条,重新连接
    if(childIndex>0){
        node.preSbing.nextSbing = node.nextSbing
    }
    if(childIndex<this.children.length-1){
        node.nextSbing.preSbing = node.preSbing
    }
    this.children.splice(childIndex,1)//删除当前节点
}
MyNode.prototype.appendParent = function(node) {
    this.parent = node
}
function MyNode(parentNode = null,{
    name="anyn",age=0
}={}){

    //这部分可以定义其他附加属性
    this.name = name
    this.age = age

    //核心属性
    this.children = []
    this.parent = parentNode
    this.nextSbing = null//下一个兄弟节点
    this.preSbing = null//上一个兄弟节点


    var _firstchild = null
    var _lastchild = null
    var _indexOfParent = null
    //存储描述符来获取firstchild
    Object.defineProperty(this,"firstchild",{
        get(){
            _firstchild = this.children[0]
            return _firstchild
        }
    })
    //存储描述符来获取lastchild
    Object.defineProperty(this,"lastchild",{
        get(){
            _lastchild = this.children[this.children.length - 1]
            return _lastchild
        }
    })
    //存储描述符来获取indexOfParent
    Object.defineProperty(this,"indexOfParent",{
        get(){
            var temp = this
            var cont = 0
            while(temp.preSbing!=null){
                temp = temp.preSbing
                cont++
            }
            _indexOfParent = cont
            return _indexOfParent
        }
    })

    this.firstchild = _firstchild
    this.lastchild = _lastchild
    this.indexOfParent = _indexOfParent
}

var parentNode = new MyNode(null,{name:"nidie",age:29})
var son1Node = new MyNode(parentNode,{name:"zhangsan",age:18})
var son2Node = new MyNode(parentNode,{name:"lisi",age:15})
var son3Node = new MyNode(parentNode,{name:"wangwu",age:19})
var son4Node = new MyNode(parentNode)

parentNode.appendChild(son1Node)
parentNode.appendChild(son2Node)
parentNode.appendChild(son3Node)
parentNode.appendChild(son4Node)
parentNode.deletChild(son1Node)
console.log(parentNode)