What exactly is DOM Extension / Wrapping?

后端 未结 1 547
清歌不尽
清歌不尽 2021-02-04 19:54

I have 2 main questions.

  1. Does extending things like Object count?

  2. What is DOM wrapping?

http://perfectionkills.c

相关标签:
1条回答
  • 2021-02-04 20:17

    No, Object is specified as part of the Javascript language, while the DOM is an API only relevant in a browser environment and is used to "access and update the content, structure and style of documents" (W3C).

    However, one of the reasons provided in that article arguing against the extension of DOM objects still applies to extending native types such as Object - namely the chance of collisions.


    Wrapping an object refers to creating a new object that references the original, but providing additional functionality through the new, wrapper object.

    For example, rather than extending a DOM Element object with a cross-browser addClass function like this:

    var element = document.getElementById('someId');
    element.addClass = function (className) {
        ...
    };
    

    You can instead define a wrapper function:

    var ElementWrapper = function (element) {
        this.element = element;
    };
    

    And add the function to its prototype:

    ElementWrapper.prototype.addClass = function (className) {
        ...
    };
    

    And "wrap" elements like this:

    var element = document.getElementById('someId');
    var wrapped = new ElementWrapper(element);
    wrapped.addClass('someClass');
    
    0 讨论(0)
提交回复
热议问题