javascript - 在另一个上下文中设置变量

标签 javascript image syntax onload strict

我有以下功能

"use strict";
function Player
{
    this.width;
    this.height;
    this.framesA = 5;

    this.image = new Image();
    this.image.onload = function ()
    {
        width = this.width;
        height = this.height / framesA;
    }
    this.image.src = "Images/angel.png";
}

我怎样才能让这段代码工作?
我希望在调用 onload 函数时将 Player 函数中的宽度和高度与图像的宽度和高度一起确定。

我需要它在严格模式下工作(必须)。

如果应该以其他方式完成此任务,请随时教授。

编辑:我更新了代码以反射(reflect)更现实的情况(我不知道这会如此复杂)

编辑2:代码的另一次更新。我没有注意到我写了 var insted 这个。抱歉。

提前致谢

最佳答案

我从您的评论中收集到的是,您希望能够从 Player 函数外部访问宽度和高度,问题是您不知道宽度和高度何时是可用。

如果这是正确的,事情就会变得有点复杂。由于您不知道图像何时加载,并且无法获得加载前的宽度和高度(除非您在 img 标记服务器端指定它们),因此您需要使用函数接受回调来访问玩家的宽度和高度。

基本上,如果宽度和高度还不知道,该函数只是将回调放入队列中。确定宽度和高度后,将调用队列中的所有函数,并将宽度和高度作为参数传递给它们。如果调用函数时已经知道尺寸,则应该立即使用正确的参数调用回调函数。

我的做法如下:

function Player() {
    'use strict';

    // Store this in a variable so the onload handler can see it.
    var that = this;
    var callbacks = [];

    this.frames = 5;

    this.getDimensions = function (callback) {
        // We don't have the dimensions yet, so put the callback in the queue.
        callbacks.push(callback);
    };

    this.image = new Image();
    this.image.onload = function () {
        var width = this.width;
        var height = this.height / that.frames;

        // Call each of the registered callbacks.
        var i;
        for (i = 0; i < callbacks.length; i += 1) {
            callbacks[i](width, height);
        }
        // Don't keep unnecessary references to the functions.
        callbacks = null;

        // We now know the dimensions, so we can replace the getDimensions
        // function with one that just calls the callback.
        that.getDimensions = function (callback) {
            callback(width, height);
        };
    };
    this.image.src = "Images/angel.png";
}

以下是访问维度的方法:

var p = new Player();
p.getDimensions(function (width, height) {
    console.log("Player's width is " + width + " and height is " + height);
});

关于javascript - 在另一个上下文中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8841380/

相关文章:

image - Laravel Assets 网址

windows - 我需要做什么才能将 DIB 转换为 BMP?

javascript - Javascript/JQuery语法不太直观?

C# 在枚举中使用数字

javascript - 在 Chart.js 工具提示中显示 PHP 数组

Javascript:多个计时器与多个计时器多个函数调用

javascript - 如何根据 Ajax 请求更改选择框选定的选项

javascript - 如何根据所选元素的高度设置父级的高度

javascript - 是否可以在不使用网络界面的情况下直接上传 Vignette 文件?

mysql - SQL建表主键和外键语法