【发布时间】:2023-01-05 19:14:18
【问题描述】:
如何创建一个类新图片()? 例子:
我向此类添加了一个原型,例如:Image.prototype.convert = function() {}
const img = new Image();
console.log(img) //will return the <img> element
而且我仍然可以执行 img.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
【问题讨论】:
-
您不得
return构造函数中的对象。您的vid不是Video实例。 -
“新视频只会返回一个类“ - 不确定你的意思,还有,那有什么问题?
-
如果您想像在
Image.prototype上创建属性一样,为什么不直接在HTMLVideoElement.prototype上创建属性? (注意 either is a bad idea 仍然) -
这很有趣@Bergi 谢谢,这篇文章已经超过 12 年了,并且讨论了当时的浏览器版本,它在今天是否仍然相关?
标签: javascript class prototype