我有以下功能
"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函数时,我希望播放器函数中的宽度和高度与图像的宽度和高度无关。
我需要它以严格的方式工作(必须)。
如果这是应该完成的另一种方式,可以自由地教书。
编辑:我更新了代码以反映更真实的情况(我不知道这会这么复杂)
编辑2:代码的另一个更新。我没有注意到我写了这篇文章。抱歉的。
提前感谢
发布于 2012-01-12 21:11:25
我从您的评论中收集到的是,您希望能够从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);
});发布于 2012-01-12 19:54:33
只要设置变量并在onload事件中执行操作,它们就会停留在范围内。
"use strict";
function Player
{
this.image = new Image();
this.image.src = "Images/angel.png";
this.image.onload = function ()
{
var width = this.width;
var height = this.height;
// Do your manipulations within the `onload` event.
}
}发布于 2012-01-12 20:19:43
以下是 Šime Vidas的真正含义
"use strict";
function Player {
this.image = new Image();
this.image.src = "Images/angel.png";
}
Player.prototype.getWidth = function() {
return this.image.width;
}或者如果您喜欢基于闭包的对象
function Player {
this.image = new Image();
this.image.src = "Images/angel.png";
this.getWidth = function() {
return this.image.width;
}
}https://stackoverflow.com/questions/8841380
复制相似问题