0

既存のオブジェクトのいくつかの文字列を置き換えることによってjavascriptオブジェクトに属性を作成しています。副作用として、this.propertyでアクセスしようとする3番目のプロパティにいくつかの追加の変更を加えたいのですが、replace関数ではこれは'master'オブジェクトの代わりにウィンドウを参照しています。this3番目のプロパティにアクセスするために使用できるように、カプセル化オブジェクトを渡すにはどうすればよいですか。

b = {
    a: 'onetwothree',
    count: 0,
    rp: function () {
        this.c = this.a.replace(/e/g, function (str, evalstr) {
            this.count++; // <-- this is refering to window.
            return 'e' + this.count
        })
    }
};
b.rp();

b.c = 'oneNaNtwothreNaNeNaN私はそれをしたいのに対してone1twothre2e3

4

3 に答える 3

2

通常、次のように、作成しているクロージャーを利用してこれを解決できます。

b = {
    a: 'onetwothree',
    count: 0,
    rp: function () {
        var self = this;             // <-- Create a variable to point to this
        this.c = this.a.replace(/e/g, function (str, evalstr) {
            self.count++;            // <-- And use it here
            return 'e' + self.count; // <-- And here (also added the ;)
        })
    }
};
b.rp();

もっと探求する(開示:両方とも私のブログへの投稿です)

于 2012-05-31T12:21:39.663 に答える
2

thisコンテキストを別の変数にキャッシュします。

rp: function () {
     var self = this; // Cache here
     this.c = this.a.replace(/e/g, function(str, evalstr) {
         return 'e' + (++self.count); // Use here
     });
}

ヒント:++ self.countは、インクリメントに新しい値を提供します。

于 2012-05-31T12:21:50.357 に答える
2
rp: function () {
    this.c = this.a.replace(/e/g, function (str, evalstr) {
        this.count++;
        return 'e' + this.count
    }.bind( this )) // <-- bind the function
}
于 2012-05-31T12:21:55.800 に答える