コメントから集めたのは、関数の外側から幅と高さにアクセスできるようにしたいということ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);
});