如何在 javascript 中复制构造函数内部的对象

How to copy objects inside constructor in javascript

我想创建自定义图像构造函数:

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"。有什么想法吗?

尝试添加类似这样的内容

var imgConstructor = function(src, width, height) {
    var img = this;
    img = new Image(width, height);
    img.onload = function(){
      // image  has been loaded
    };
    img.src = src;
    return img;
}

But I want to do with constructor, using new. Any ideas?

不,那不可能。毕竟,您将无法继承 Image。如果您需要使用自己的方法 "instances",最好创建一个包装器对象(就像在构造函数中执行 this.img = new Image(…))。

使用工厂函数完全没问题,在这里似乎很合适。如果你出于某种原因想使用 new,你可以在你的工厂函数上使用 new,它仍然可以工作(尽管产生 Image,而不是 imgConstructor 的实例).

继承在这里帮不了你。因为Image can't be inherited. See why here

基本解释:

var a = new Image();
console.log(a.constructor); // Should be function Image() { [native code] }
// OUTPUT: function HTMLImageElement() { [native code] }

var b = new HTMLImageElement();
// Uncaught TypeError: Illegal constructor

所以,你的解决方案是正确的。

编辑: @user86745458 的解决方案有效,但正如@Bergi 所说:

When someone calls new imgConstructor, one would usually expect that the result is an instance of imgConstructor. It is not always, as when the constructor returns an object explicitly that might be something different.

尝试应用旧解决方案(来自@user86745458)并检查:

new imgConstructor() instanceof imgConstructor
// OUTPUT: false 
imgConstructor() instanceof imgConstructor
// OUTPUT: false
imgConstructor() instanceof Image
// OUTPUT: true