簡體   English   中英

String.replace; 按功能替換結果問題

[英]String.replace; replace by function result problem

我有這段代碼:

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.

PS對不起,我的英語不是我的母語。

也許嘗試:

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的大多數事情而言)

這就是原型和其他人所做的

// Monkey Patching, not everyone likes it
Function.prototype.bind = function( obj ) {
    var _this = this;
    return function() {
        return _this.apply( obj, arguments )
    }
}

現在您可以執行此操作

var myObj = function () {
   this.complex = function (text) { /* long piece of code */ }
   this.parse = function(text) {
     return text.replace(/valid_pattern/gi, function ($1) { return this.complex($1); }.bind( this ) );
   }
}

O = new myObj();
alert( O.parse( 'some text' );

為此聲明一個變量。

var myObj = function () {
  var foo = this.complex = function (text) { /* long piece of code */ }
  this.parse(text) {
    return text.replace(/valid_pattern/gi, foo );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM