为什么javascript函数的返回值未定义? [英] why is return value of javascript function undefined?

查看:187
本文介绍了为什么javascript函数的返回值未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个检测图像大小的功能,我想让它返回一个包含宽度和高度的对象。在下面的代码中,函数中的sz.width和sz.height 保存了值,但是在返回值之后,它是未定义的。我缺少什么?

I've got a function to detect the size of an image, and I want it to return an object that contains both the width and height. In the code below, sz.width and sz.height within the function hold the values, but after they return the value it's undefined. What am I missing?

     function getImgSize(imgSrc) {
        var newImg = new Image();

        newImg.onload = function() {
          var height = newImg.height;
          var width = newImg.width;

          function s() {}
          sz = new s();
          sz.width = width;
          sz.height = height;
          $('#infunc').text("in function, w = "+sz.width+", h = "+sz.height);
          return sz;
        }
        newImg.src = imgSrc; // this must be done AFTER setting onload
      }

var sz = getImgSize("http://lorempixel.com/output/fashion-q-c-1920-1920-4.jpg");
$('#outfunc').text("outside function, w = "+sz.width+", h = "+sz.height);

jsfiddle: http://jsfiddle.net/forgetcolor/LbxA3/

jsfiddle: http://jsfiddle.net/forgetcolor/LbxA3/

推荐答案

函数 getImgSize 设置图像加载然后终止。稍后,当图像加载时,将调用匿名onload函数并正确计算大小,然后将其返回给一个不受欢迎的DOM引擎...

The function getImgSize sets up the image loading and then terminates. Later, when the image loads, the anonymous onload function is invoked and correctly calculates the size, then returns it, to an uncaring DOM engine...

你可能想知道你如何做你想做的事。简短的回答:你做不到。这是你最接近的地方:

You're probably wondering how you can do what you want. Short answer: you can't. Here's the closest you can get:

  function getImgSize(imgSrc, callback) {
    var newImg = new Image();

    newImg.onload = function() {
      ... // blah-blah blah
      callback(sz);
    }
    newImg.src = imgSrc;
  }
  getImgSize("http://lorempixel.com/output/fashion-q-c-1920-1920-4.jpg",
            function(sz) {
              $('#outfunc').text("in callback, w = "+sz.width+
                                 ", h = "+sz.height);
            });

我实际上是来这里写的:

I actually came here to write:


//这必须在设置onload后完成

// this must be done AFTER setting onload

这就是我打赌你的问题所在。
//这必须在设置onload后完成

That's what I bet your problem was. // this must be done AFTER setting onload

这篇关于为什么javascript函数的返回值未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆