使用对象包装器来扩展JavaScripts DOM? [英] Using object wrappers to extend the JavaScripts DOM?

查看:106
本文介绍了使用对象包装器来扩展JavaScripts DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向JavaScript DOM添加简单的函数,例如一个 addClass 函数,我首先用以下代码实现了它:

I'm trying to add simple functions to the JavaScript DOM, e.g. an addClass function, I implemented this first with the following code:

Element.prototype.addClass = function(className) {
    this.className += ' ' + className;
}; 

但经过多次阅读后( http://perfectionkills.com/whats-wrong-with-extending-the-dom/ 很好)看来这是一种可怕的方式由于多种原因扩展DOM。

However after much reading (http://perfectionkills.com/whats-wrong-with-extending-the-dom/ was good) it seems this is a terrible way to extend the DOM for a number of reasons.

上述文章指出:


DOM
扩展程序的最常见替代方法之一是对象包装器

哪个好,显然普遍的共识是如果你想扩展DOM就使用Object包装器。问题是我找不到任何关于你如何实际使用对象包装来扩展DOM的好例子。

Which is fine, apparently the general consensus is to use Object wrappers if you want to extend the DOM. The problem is I can't find any good examples anywhere on how you actually use object wrappers to extend the DOM ...

任何人都可以举个例子来说明如何这样做?也许使用上面的代码?

Can anybody give me an example of how to do so? Maybe using the above code?

推荐答案

对象包装器比扩展更昂贵,因为你需要创建一个新对象,但它们是更安全。

Object wrappers are more expensive than extensions because you need to create a new object, but they are safer.

只包含一个元素的简单实现可能如下所示:

A simple implementation that wraps only a single element could look like this:

(function() {
    window.wrap = function(el) {
        return new Wrapper(el);
    };

    function Wrapper(el) {
        this.element = el;
    }

    Wrapper.prototype.addClass = function(cls) {
        if (this.element)
            this.element.className += " " + cls;
    }
    Wrapper.prototype.swap = function(el) {
        this.element = el;
    }
})();

然后你可以创建一个新的包装器,为了提高效率,你可以将它重用于各种元素。

Then you could make a new wrapper, and to be more efficient, you could reuse it with various elements.

var wrp = wrap(document.body);

wrp.addClass("foo");
wrp.swap(document.body.firstElementChild);
wrp.addClass("bar");

您可以实现的另一个功能是添加返回此内容; 到所有包装器方法。这样,如果你愿意,你可以链接你的函数调用。

Another feature you could implement would be to add return this; to all the wrapper methods. That way you could chain your function calls if you like.

var wrp = wrap(document.body);

wrp.addClass("foo")
   .swap(document.body.firstElementChild)
   .addClass("bar");

你也可以实现你的包装器来保存多个元素,如数组索引,或更好,简单持有一个元素数组。

You could also implement your wrapper to hold multiple elements at numeric indices like an Array, or better, simply hold an Array of elements.

这篇关于使用对象包装器来扩展JavaScripts DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆