-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!

4
  • 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() ? Commented Sep 30, 2013 at 21:19
  • 2
    Your function test() doesn't return anything only your img.load returns and that is async as well.. Commented Sep 30, 2013 at 21:19
  • 2
    This will never work because it's async. This is about ajax, but the explanation applies to your case too: stackoverflow.com/questions/14220321/… Commented Sep 30, 2013 at 21:32
  • stackoverflow.com/questions/10694779/… Commented Sep 30, 2013 at 21:41

3 Answers 3

3

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

return in your code belongs to the anonymous callback function.

Sign up to request clarification or add additional context in comments.

1 Comment

So, what's your solution?
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.

Comments

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

Comments

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.