0

I've got a function taking in some parameters, and I would like to assign the parameter to a value in an if statement. However, the value i'm assigning is different in other parts of the function. I'm sure this is due to scope, but i don't know how to fix it.

this.img = function(sx, sy, img, sw, sh, dx, dy, dw, dh) {
    sw = 0;
    sh = 0;
    image.addEventListener('load', function() {
        if(found) {
            sw = this.width;
            sh = this.height;
            console.log(sw + ' ' + sh);
        }
    })
    console.log(sw + ' ' + sh);
}

Just so you know, the "if(found)" is being entered(i'm changing the boolean elsewhere). The first console.log is returning the proper values, 225, 225. However the second one returns 0, 0.

If anyone knows whats wrong with my scope here, that would be great.

dwib
  • 583
  • 4
  • 19
  • 1
    What result do you expect? If by _“The first console.log is returning the proper values, 225, 225”_ you mean the `console.log` inside the `if` statement, then everything works as expected, doesn’t it? Use your values there. Do you expect the second `console.log` (outside the `load` listener) to also log `225, 225`? Why? – Sebastian Simon Dec 25 '18 at 16:40
  • Ok, sorry, I'm just gonna use the values inside the if statement – dwib Dec 25 '18 at 16:42
  • 1
    The anonymous function you're passing to `image.addEventListener()` isn't called until later, when the image has actually loaded. The `console.log()` at the bottom however runs right away, when both values are still zero. –  Dec 25 '18 at 16:55

0 Answers0