从(扩展)HTML元素中进行子类化?

Ase*_*ore 7 html javascript dom

如果我可以创建自己的扩展HTML元素类的类,例如HTMLDivElement或HTMLImageElement,我会喜欢它.

假设标准继承模式:

// class A:

function ClassA(foo) {
    this.foo = foo;
}

ClassA.prototype.toString = function() {
    return "My foo is " + this.foo;
};

// class B:

function ClassB(foo, bar) {
    ClassA.call(this, foo);
    this.bar = bar;
}

ClassB.prototype = new ClassA();

ClassB.prototype.toString = function() {
    return "My foo/bar is " + this.foo + "/" + this.bar;
};
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚构造函数中要调用的内容:

function Image2() {
    // this doesn't work:
    Image2.prototype.constructor.call(this);
    // neither does this (only applies to <img>, no equivalent for <span> etc.):
    Image.call(this);
}

Image2.prototype = new Image(); // or document.createElement("img");

Image2.prototype.toString = function() {
    return "My src is " + this.src;
};
Run Code Online (Sandbox Code Playgroud)

这不可能吗?还是有某种方法?谢谢.=)

min*_*des 5

好吧,这个问题需要根据当前技术进行更新。

HTML5 为您提供了创建自定义元素的方法。您需要通过注册您的元素document.registerElement,然后您可以像任何其他标签一样使用它。该功能已在最新的 Chrome 中提供。我不确定其他浏览器的情况。

更多详细信息请参见此处:

http://www.html5rocks.com/en/tutorials/webcomponents/customelements/


Ase*_*ore 1

不,你不能。(至少在当今低至 IE6 的浏览器中并不可靠;我不知道最近在尖端浏览器中情况是否有所改变。)