我尝试创建 HTMLDivElement 的子类,但出现错误:Uncaught TypeError: Illegal constructor
var subC = function() {
HTMLDivElement.call(this);
//....
};
subC.prototype = Object.create(HTMLDivElement.prototype);
最佳答案
你不能对 DOM api 的大部分进行子类化,尤其是像 Node、Element 这样的东西......
为什么?因为涉及到复杂的依赖注入(inject),所以需要通过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 并期望它们正常运行。
关于javascript - 创建 HTMLDivElement 的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22795203/