Search code examples
javascriptimageobjectconstructorsrc

How to copy objects inside constructor in javascript


I want to create a custom image constructor:

var image1 = new imgConstructor("picture.png", 100, 50);

I have tried:

var imgConstructor = function(src, width, height) {
    this = new Image(width, height);
    this.src = src;
}

but this = new Image()is invalid.

I know I can do it with factory function like:

var imgConstructor = function(src, width, height) {
    var img = new Image(width, height);
    img.src = src;
    return img;
}
var image1 = imgConstructor("picture.png", 100, 50);

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


Solution

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

    No, that's not possible. You won't be able to subclass Imageafter all. If you needed "instances" with your own methods, better create a wrapper object (like doing this.img = new Image(…) in your constructor).

    Using a factory function is totally fine, it just seems to be appropriate here. If you want to use new for some reason, you can use new on your factory function and it will still work (though yielding the Image, not an instance of imgConstructor).