1

これが私がこれまでに持っているものです:http://jsfiddle.net/nxCFn/

var il = new ImageLoader();

function ImageLoader() {
    this.n = 2;

    this.load = function() {
        //obviously, the this = the image and not the original instance of ImageLoader :(
        this.n++;
        console.log(this.n);
    }

    this.imgnam = "http://www.google.com/images/errors/logo_sm.gif";

    this.img = new Image();
    this.img.src = this.imgnam;
    this.img.onload = this.load;
}​

画像がポイントから.load() this画像に呼び出しているためです。ロードポイントからそれが「属する」インスタンスまで作成しloadたいと思います。thisImageLoader

4

3 に答える 3

1

ローカル変数への参照をコピーしthis、イベントハンドラーを無名関数にして、ローカル変数が関数のクロージャにキャッチされるようにします。

var that = this;

this.img.onload = function() { that.load() };
于 2012-09-08T14:31:27.877 に答える
1
var that = this;
this.img.onload = function () { that.load();}
于 2012-09-08T14:31:44.517 に答える
1

使用するFunction.prototype.bind

this.img.onload = this.load.bind(this);

または、インスタンスごとに新しい関数を作成するため、ここで使用できます。

this.load = function() {
    this.n++;
    console.log(this.n);
}.bind(this);


this.img.onload = this.load;

古いブラウザをサポートするために、代わりに独自のバインダー関数を作成できます。

function _binder(func, ctx /*, arg1, argn */) {
    var _slice = Array.prototype.slice,
        bound_args = _slice.call(arguments, 2);
    return function() {
        return func.apply(ctx, bound_args.concat(_slice.call(arguments)));
    }
}

次に、これを行います。

this.img.onload = _binder(this.load, this);
于 2012-09-08T14:33:48.920 に答える