如何创建一个类,如new Image()?例子:
我给这个类添加了一个原型:Image.prototype.convert = function() {}
const img = new Image();
console.log(img) //will return the <img> element
我仍然可以执行image。convert();
所以我创建了一个这样的类:class Video {
constructor() {
return document.createElement("VIDEO");
}
convert() {
console.log("converted");
}
}
这样我将无法访问new Video.convert(),因为我将得到的只是元素。然而,如果我不在构造函数中返回元素,new Video将只返回一个类。
所以肩并肩:
const img = new Image();
const vid = new Video();
console.log(img) //<img>
console.log(vid) //<<video>
img.convert() // *converted*
vid.convert() //error: vid.convert is not a function
在收到有帮助的评论后,我意识到扩展DOM并不像我最初想的那样好。因为它可能会导致与潜在的其他库的碰撞,降低性能等。即使包装可以解决碰撞问题,编写它也不那么方便,而且仍然存在性能问题。
我想一些替代方案只是编写实用程序函数,Helper对象甚至使用CustomElementRegistry。