我从您的评论中收集到的是您希望能够从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);
});