Javascript。为什么这个代码不起作用?

Javascript. Why does not work this code?

我叫不出属性身高:

当我调用高度属性时,消息得到0。但它应该给我1152。

var fondoJuego=new FondoJuego();
fondoJuego.setFondoSrc("tituloNV.png");
alert("Altura "+fondoJuego.getFondo().height);

var FondoJuego=function(){
            this.fondo=new Image();
            this.getFondo=function(){
                return this.fondo;
            };
            this.getFondoSrc=function(){
                return this.fondo.src;
            };
            this.setFondo=function(fondoAux){
                this.fondo=fondoAux;
            };
            this.setFondoSrc=function(fondoSrcAux){
                this.fondo.src=fondoSrcAux;
            };
        };

谢谢

发生这种情况是因为图像需要一些时间才能加载 async fashion

我们以Google的涂鸦为例:

var imageAsync = new Image();
imageAsync.src = "https://www.google.com.br/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png?t=" + (+new Date);
console.log(imageAsync.height);

var imageSync = new Image();
imageSync.src = "https://www.google.com.br/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png?t=" + (+new Date);
imageSync.onload = function () {
  console.log(this.height);
}

Returns 0 和 92.

您将需要收听 load 事件。

这应该有效:

function getHeight() {
    alert("Altura " + fondoJuego.fondo.height );
    return true;
}

var FondoJuego = function() {

    this.fondo = new Image();

    this.fondo.addEventListener("load", function(){
        getHeight();
    });

    this.getFondo=function(){
        return this.fondo;
    };

    this.getFondoSrc=function(){
        return this.fondo.src;
    };

    this.setFondo=function(fondoAux){
        this.fondo=fondoAux;
    };

    this.setFondoSrc=function(fondoSrcAux){
        this.fondo.src=fondoSrcAux;
    };
};

var fondoJuego = new FondoJuego();

fondoJuego.setFondoSrc("tituloNV.jpg");

检查这个 jsfiddle:https://jsfiddle.net/dm7dqajf/