-2

If I do this:

test();

function test(){
  $('img').load(function(){
  alert(this.width);
 })
}

An alert is shown with the correct image width.

But, when I do this:

alert(test());

function test(){
  $('img').load(function(){
  return this.width;
 })
}

... the alert shows 'undefined'

Both examples are run from within the $(document).ready function. I think it got something to do with load(). But I can't figure out why alert works, but return doesn't.

thx!

user63457
  • 591
  • 2
  • 7
  • 18
  • 2
    What are you expecting, a function returns undefined when nothing else is returned, and returning from the callback does not return anything from test() ? – adeneo Sep 30 '13 at 21:19
  • 2
    Your function `test()` doesn't return anything only your `img.load` returns and that is async as well.. – PSL Sep 30 '13 at 21:19
  • 2
    This will never work because it's async. This is about ajax, but the explanation applies to your case too: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – bfavaretto Sep 30 '13 at 21:32
  • http://stackoverflow.com/questions/10694779/why-is-return-value-of-javascript-function-undefined?rq=1 – Blaise Sep 30 '13 at 21:41

3 Answers3

3

Your test function always returns undefined because it doesn't have return statement.

return in your code belongs to the anonymous callback function.

Pawel Furmaniak
  • 4,648
  • 3
  • 29
  • 33
0

I am not a JS ninja yet but I feel this has something to do with scopes. Im suspecting the this keyword in both situations are pointing to different objects.

final: in the second example at the moment alert is called, there is nothing to return to it for it to display anything. This is because the return is defined asynchronously; it will return whenever the image is finished loading.

nemo
  • 593
  • 2
  • 8
  • 22
0

Images are loaded asynchronously, so you better forget about return in this case. (See a detailed explanation at How do I return the response from an asynchronous call?).

If you have to handle the image's dimensions after loading, do it from the callback:

function test(){
    $('img').load(function(){
        // If you need to use this.width or this.height, do it from here
    });
}

You can also pass a callback to test:

function test(callback){
    $('img').load(callback);
}
function doSomething() {
    alert(this.width);
}
test(doSomething);
Community
  • 1
  • 1
bfavaretto
  • 71,580
  • 16
  • 111
  • 150