How to copy objects inside a constructor in javascript

I want to create my own image constructor:

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

      

I 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 a 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 the constructor using "new". Any ideas?

+3


source to share


3 answers


But I want to do with a constructor using new

. Any ideas?

No, It is Immpossible. After all, you won't be able to subclass Image

. If you need "instances" with your own methods, it is better to create a wrapper object (for example, do this.img = new Image(…)

in your constructor).



Using a factory function is totally fine, it just seems appropriate. If you want to use new

for any reason, you can use a new

factory in your function and it will still work (although it gives Image

, not an instance imgConstructor

).

+3


source


Inheritance won't help you here. Because the Image cannot be inherited. See why here

Basic explanation:

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

      

So, your solution is corret.



EDIT: Solution from @ user86745458 works, but as @Bergi said:

When someone calls a new imgConstructor, you can usually expect the result to be an instance of imgConstructor. It is not always like when a constructor explicitly returns an object, which may be different.

Try the old solution (from @ user86745458) and check:

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

      

+1


source


Try adding something like this

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;
}

      

0


source







All Articles