代码之家  ›  专栏  ›  技术社区  ›  Iter Ator

正在创建HTMLDivElement的子类

  •  1
  • Iter Ator  · 技术社区  · 12 年前

    我试图创建HTMLDivElement的子类,但遇到了一个错误: Uncaught TypeError: Illegal constructor

    var subC = function() {
        HTMLDivElement.call(this);
    
        //....
    };
    
    subC.prototype = Object.create(HTMLDivElement.prototype);
    
    2 回复  |  直到 12 年前
        1
  •  0
  •   mpm    12 年前

    您不能子类化 最 DOM api,尤其是Node、Element。。。

    为什么?因为它们涉及复杂的依赖注入,所以需要通过document.createElement构建Element。

    你唯一能做的就是使用合成:

    function subC = function(htmlElement){
       this.htmlElement=htmlElement;
    }
    

    然后可以在subC中公开htmlElement的一些财产

    Object.keys(this.htmlElement).forEach(function(k){this[k]=this.htmlElement[k];},this);
    

    在构造函数中,作为快捷方式。

    您需要包装您想要使用的每个方法,但我不会冒险将Element.prototype方法添加到subC中,并期望它们正确运行。

        2
  •  0
  •   Musa    12 年前

    怎么样

    function subC() {
        //w/e
    }    
    subC.prototype = document.createElement('div');
    var x = new subC();
    alert(x instanceof HTMLDivElement);
    

    http://jsfiddle.net/vK96X/