0

Good afternoon, I am playing a little in javascript and I have a "class" of this form:

var Card = function(url,c){
            ...
            this.img = new Image();
            this.widthCurr = 0;
            this.heightCurr = 0;
            this.img.onload = this.imageLoaded()
            this.img.src = this.url;
        };

and a method defined as

Card.prototype = {
            imageLoaded : function(){
                //my goal is to initialize this.widthCurr and this.heightCurr
                console.log(this.img.width);
            },

            ...
        };

Basically my goal is to initialize widthCurr and heightCurr with actual width and height of img, when the img is loaded. I created new object and console.log command in imageLoaded keeps saying "0" so at that time, image is not loaded. I tried a few modifications, but no one seemed to work. Am I missing something important? How or where should I set these values?

1 Answer 1

3
        this.img.onload = this.imageLoaded()

You just called the function, and assigned its result to this.img.onload.

Instead, you need to assign the function itself, and you need to bind this:

        this.img.onload = this.imageLoaded.bind(this)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for quick reply, I can probably see the difference, but when I change the code, the body of imageLoaded function seems not to be executed at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.