我有这段代码:
var myObj = function () {
this.complex = function (text) { /* long piece of code */ }
this.parse(text) {
return text.replace(/valid_pattern/gi, function ($1) { return this.complex($1); } );
}
}
当然,调用 this.complex($1) 不会成功,因为我处于匿名函数的范围内。我也无法使用 .call(this) 语句重新调整匿名函数的范围,因为在这种情况下,我会丢失通过 String.replace 传递给函数的参数。 >.
到目前为止,我正在使用该对象的具体实例。这是我的解决方案:
var instance = new myObj;
var myObj = function () {
this.complex = function (text) { /* long piece of code */ }
this.parse(text) {
return text.replace(/valid_pattern/gi, function ($1) { return instance.complex($1); } );
}
}
到目前为止,它足以满足我的需求,但是我想知道是否有任何通用的解决方案来解决这个问题。到目前为止,唯一对我有用的想法是:
function ($1) { return (new myObj).complex($1); }
...存在严重的性能问题。任何想法将不胜感激。
--D.
P。 S. 抱歉我的英语,这不是我的母语。
最佳答案
也许可以尝试一下:
var myObj = function () {
this.complex = function (text) { /* long piece of code */ }
this.parse(text) {
var that = this;
return text.replace(/valid_pattern/gi, function ($1) { return that.complex($1); } );
}
}
这是最有用的技巧之一:-)
更新: 这个技巧不是我的,我是从:Douglas Crockford 学到的(就像我所知道的关于 Javascript 的大部分内容一样)。
关于javascript - 字符串替换;用函数替换结果问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/424826/