我想创建一个自定义图像构造函数:
var image1 = new imgConstructor("picture.png", 100, 50);
我努力了:
var imgConstructor = function(src, width, height) {
this = new Image(width, height);
this.src = src;
}
但this = new Image()
无效。
我知道我可以使用工厂功能来做到这一点:
var imgConstructor = function(src, width, height) {
var img = new Image(width, height);
img.src = src;
return img;
}
var image1 = imgConstructor("picture.png", 100, 50);
但是我想使用“ new”来处理构造函数。有任何想法吗?
但是我想使用构造函数
new
。有任何想法吗?
不,那不可能。Image
毕竟,您将无法继承子类。如果您需要使用自己的方法使用“实例”,则最好创建一个包装对象(就像this.img = new Image(…)
在构造函数中一样)。
使用工厂函数是完全可以的,在这里似乎很合适。如果您new
出于某种原因要使用,则可以new
在工厂函数上使用它,它仍然可以工作(尽管产生Image
,而不是的实例imgConstructor
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句