从DOM类/类型

时间:2016-08-22 20:48:07

标签: javascript dom extend

我做了一些关于扩展DOM类的谷歌搜索,我主要看到:
- 将您自己的函数添加到Element.prototype(或更具体的元素)
- 在每个对象创建时将自己的函数附加到对象的每个实例上 用常规对象包裹DOM元素

我已经提出了以下扩展DOM的方法,并且在我测试之后似乎完全按照我想要的方式工作(但只是简单的测试)。

function X() { //my class X extending HTMLDivElement
    //skipping 'this', creating my own object instead and setting the prototype to X myself
    let x=document.createElement('div');
    Object.setPrototypeOf(x, X.prototype);
    return x;
}
X.prototype=Object.create(HTMLDivElement.prototype);
X.prototype.m1=function() { console.log('method m1 from X!!!'); };

let x=new X();
document.body.appendChild(x);

x.m1();

function XX() { //my class XX extending X
    //skipping 'this' also, creating my own object from X instead, and chainning the prototype XX
    //the prototype chainning is now HTMLDivElement -> X -> XX
    let xx=new X();
    Object.setPrototypeOf(xx, XX.prototype);
    return xx;
}
XX.prototype=Object.create(X.prototype);
XX.prototype.m1=function() { console.log('method m1 from XX!!!'); };

let xx=new XX();
document.body.appendChild(xx);
xx.m1();

console.log("x instanceof HTMLDivElement?" + (x instanceof HTMLDivElement)); //true
console.log("x instanceof X?" + (x instanceof X)); //true
console.log("x instanceof XX?" + (x instanceof XX)); //false
console.log("xx instanceof HTMLDivElement?" + (xx instanceof HTMLDivElement)); //true
console.log("xx instanceof X?" + (xx instanceof X)); //true
console.log("xx instanceof XX?" + (xx instanceof XX)); //true

我创建了100,000个这样的对象并将它们放在document.body中,它似乎与使用普通div类似。

这有什么问题吗? /有没有人做过这样的事? 我已阅读并了解使用setPrototypeOf时的问题。

0 个答案:

没有答案
相关问题