Javascript 更换';s功能访问电子封装对象?
通过替换现有对象中的一些字符串,我在javascript对象中创建了一个属性,作为副作用,我想对第三个属性进行一些额外的更改,我尝试使用this.property访问该属性,但是在replace函数中,它指的是窗口,而不是我的“master”对象。如何传入封装对象,以便使用Javascript 更换';s功能访问电子封装对象?,javascript,function,replace,Javascript,Function,Replace,通过替换现有对象中的一些字符串,我在javascript对象中创建了一个属性,作为副作用,我想对第三个属性进行一些额外的更改,我尝试使用this.property访问该属性,但是在replace函数中,它指的是窗口,而不是我的“master”对象。如何传入封装对象,以便使用this访问第三个属性 b = { a: 'onetwothree', count: 0, rp: function () { this.c = this.a.replace(/e/g,
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={
a:‘一对三’,
计数:0,
rp:函数(){
this.c=this.a.replace(/e/g,函数(str,evalstr){
this.count++;//您通常可以通过使用正在创建的闭包来解决此问题,如下所示:
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();
b={
a:‘一对三’,
计数:0,
rp:函数(){
var self=this;//您通常可以通过使用正在创建的闭包来解决此问题,如下所示:
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();
b={
a:‘一对三’,
计数:0,
rp:函数(){
var self=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在递增后给出新值。将此
上下文缓存在另一个变量中
rp: function () {
var self = this; // Cache here
this.c = this.a.replace(/e/g, function(str, evalstr) {
return 'e' + (++self.count); // Use here
});
}
rp: function () {
this.c = this.a.replace(/e/g, function (str, evalstr) {
this.count++;
return 'e' + this.count
}.bind( this )) // <-- bind the function
}
Protip:++self.count在递增后给出新值。rp:function(){
rp: function () {
this.c = this.a.replace(/e/g, function (str, evalstr) {
this.count++;
return 'e' + this.count
}.bind( this )) // <-- bind the function
}
this.c=this.a.replace(/e/g,函数(str,evalstr){
这个.count++;
返回'e'+this.count
}.bind(this))/rp:function(){
this.c=this.a.replace(/e/g,函数(str,evalstr){
这个.count++;
返回'e'+this.count
}.bind(this))//谢谢您的“this”,但我仍然更喜欢运算符优先语法(,key:val而不是key:val),@drjerry当然,但是您的原始代码对于其他人来说是完全不可读的,所以我只是通过一个更漂亮的工具来运行它,该工具在后面加逗号。请注意bind()
是一个相对较新的功能,并非在所有浏览器中都可用(safari mobile被它卡住了),您可能需要参考以获得解决方法。谢谢您的“this”,但我仍然更喜欢运算符优先语法(,key:val而不是key:val,)@drjerry当然可以,但是你的原始代码对于其他人来说是完全不可读的,所以我只是通过一个漂亮的工具运行了它,在后面加了逗号。请注意,bind()
是一个相对较新的函数,不是所有浏览器都可以使用(safari mobile被它卡住了),你可能需要参考它来解决问题。