我有以下功能
"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/