关于修改Node原型的担忧

时间:2012-09-21 22:08:56

标签: javascript jquery dom nodelist

所以,为了好玩,我决定看看我是否可以模仿jQuery的语法/功能。事实证明这很简单(当不担心跨浏览器/传统兼容性时)。你可以看到我到目前为止所做的工作:http://jsfiddle.net/FPAaM/3/

现在,为了不踩到其他第三方JavaScript库的脚趾,在向NodeNodeList原型添加功能时应注意哪些问题?

Node.prototype.text = function(txt){
    var chld = this.childNodes;
    while(chld[0]) this.removeChild(chld[0]);

    this.appendChild(document.createTextNode(txt));

    return this;
};
NodeList.prototype.text = function(txt){
    for (var i = 0; i < this.length; i++)
        this[i].text(txt);

    return this;
};
Node.prototype.css = function(tag, val){
    if (val != undefined)
        this.style[tag] = val;
    else
        return this.style[tag];

    return this;
};
NodeList.prototype.css = function(tag, val){
    for (var i = 0; i < this.length; i++)
        this[i].css(tag, val);

    return this;
};
Node.prototype.clk = function(cbk){
    this.addEventListener("click", cbk, false);

    return this;
};
NodeList.prototype.clk = function(cbk){
    for (var i = 0; i < this.length; i++)
        this[i].clk(cbk);

    return this;
};

var $ = function(args){
    if (typeof args == "function")
        document.addEventListener("DOMContentLoaded", args, false);

    if (typeof args == "string")
        return document.querySelectorAll(args);

    return args;
};

$(function(){
    $("div.fancy").text("Poor man's jQuery!")
        .css("color", "red")
        .clk(function(e){
            if (this.css("color") == "red")
                $(this).css("color", "green");
            else
                this.css("color", "red");
        });
});

1 个答案:

答案 0 :(得分:0)

NodeNodeList 主机对象 。你不应该扩展它们。更好的方法是使用包装器(如jQuery)。

选中此项: What's wrong with extending the DOM