0

我通过替换现有对象中的一些字符串来在 javascript 对象中创建一个属性,作为副作用,我想对第三个属性进行一些额外的更改,我尝试使用 this.property 访问它但是在替换函数中这是指的是窗口而不是我的“主”对象。我怎样才能传入封装对象,以便我可以this用来访问第三个属性。

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
     });
}

Protip: ++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 回答