封装原生JS的思路

以下用于记录封装JS的思路,而现有的各种前端库都是用类似的思路实现的,只是实现的功能要更加强大,实现细节也更加巧妙

  • 首先先封装两个函数,用于更方便的取元素的兄弟节点以及为元素添加class
function getSiblings(node) {
    var allChildren = node.parentNode.children
    
    var array = {
        length: 0
    }

    for(let i = 0; i < allChildren.length; i ++) {
        if(allChildren[i] !== node) {
            array[array.length] = allChildren[i]
            array.length += 1
        }
    }

    return array
}

// console.log(getSiblings(items2))

// 封装第二个函数,用于方便地给元素添加class
function addClass(node, classes) {
    for(let key in classes) {
        if(classes[key]) {
            node.classList.add(key)
        } else {
            node.classList.remove(key)
        }
        // 以上几行可以优化成以下的代码
        // var value = classes[key]
        // var methodName = value ? 'add' : 'remove'
        // obj.x与obj['x']是等价的
        // node.classList[methodName](key)
    }
}

// addClass(items2, {a:true, b:false, c:true})
  • 但是直接使用全局变量来定义两个函数,容易污染全局变量,造成变量名冲突覆盖,那么我们可以定义命名空间
// 自定义命名空间
window.xxdom = {}
xxdom.getSiblings = getSiblings
xxdom.addClass = addClass

// 或者可以直接在定义函数的时候就使用命名空间
// xxdom.getSiblings = function() {}

// console.log(xxdom.getSiblings(items2))
// xxdom.addClass(items2, {a:true, b:false, c:true})
  • 虽然解决了污染全局变量的问题,但是函数调用不如调用对象的方法那么符合使用习惯,我们可以用方法一:修改Node对象(构造函数)的原型
Node.prototype.getSiblings = function() {
    var allChildren = this.parentNode.children
    
    var array = {
        length: 0
    }

    for(let i = 0; i < allChildren.length; i ++) {
        if(allChildren[i] !== this) {
            array[array.length] = allChildren[i]
            array.length += 1
        }
    }

    return array
}

// console.log(items4.getSiblings())

Node.prototype.addClass = function(classes) {
    for(let key in classes) {
        if(classes[key]) {
            this.classList.add(key)
        } else {
            this.classList.remove(key)
        }
    }
}

// items4.addClass({a:true, b:false, c:true})

  • 或者方法2:重新定义一个构造函数
window.Node2 = function(node) {
    return {
        getSiblings: function() {
            var allChildren = node.parentNode.children
    
            var array = {
                length: 0
            }

            for(let i = 0; i < allChildren.length; i ++) {
                if(allChildren[i] !== node) {
                    array[array.length] = allChildren[i]
                    array.length += 1
                }
            }

            return array
        },
        addClass: function(classes) {
            for(let key in classes) {
                if(classes[key]) {
                    node.classList.add(key)
                } else {
                    node.classList.remove(key)
                }
            }
        }
    }
}

var node2 = Node2(items3)
// console.log(node2.getSiblings())
// node2.addClass({a:true, b:false, c:true})

使用类似的思路就可以完成作业

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容