从(扩展)HTML元素进行子类化? [英] Subclassing from (extending) an HTML element?
本文介绍了从(扩展)HTML元素进行子类化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设标准继承模式:
/ class A:
function ClassA(foo){
this.foo = foo;
}
ClassA.prototype.toString = function(){
返回我的foo是+ this.foo;
};
// class B:
function ClassB(foo,bar){
ClassA.call(this,foo);
this.bar = bar;
}
ClassB.prototype = new ClassA();
ClassB.prototype.toString = function(){
返回我的foo / bar是+ this.foo +/+ this.bar;
};
我无法弄清楚构造函数中调用的内容:
function Image2(){
//这不工作:
Image2.prototype.constructor.call(this);
//也不会(仅适用于< img>,不等同于< span>等):
Image.call(this);
}
Image2.prototype = new Image(); //或document.createElement(img);
Image2.prototype.toString = function(){
return我的src是+ this.src;
};
这是不可能的吗?还是有一些方法?谢谢。 =)
解决方案
不,你不能。 (至少不可靠地跨越今天的浏览器到IE6;我不知道最新的浏览器的情况最近如何变化)。
I'd love it if I could make my own class that extended an HTML element class, e.g. HTMLDivElement or HTMLImageElement.
Assuming the standard inheritance pattern:
// 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;
};
I'm not able to figure out what to call in the constructor:
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;
};
Is this just not possible? Or is there some way? Thanks. =)
解决方案
No you can't. (At least not reliably across today's browsers down to IE6; I don't know if the situation has recently changed in cutting-edge browsers.)
这篇关于从(扩展)HTML元素进行子类化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文