String.replace; replace by function result problem
<p>I have this piece of code:</p>

<pre><code>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); } );
   }
}
</code></pre>

<p>Of course calling <strong>this.complex($1)</strong> won't do the trick, because I'm in the scope of the anonymous function. I can't re-scope the anonymous function using <strong>.call(this)</strong> statement either, because in th ta case I would lose the parameters passed to the function by <em>String.replace</em>.</p>

<p>So far I'm using the concrete instance of the object. This is my solution:</p>

<pre><code>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); } );
   }
}
</code></pre>

<p>So far it's sufficient to my needs, but <strong>I'm wondering if there is any universal solution</strong> to this problem. The only idea that has worked for me so far is this:</p>

<pre><code>function ($1) { return (new myObj).complex($1); }
</code></pre>

<p>... which suffers from serious performance issues. Any ideas would be greatly appreciated.</p>

<p>-- D.</p>

<p>P. S. Sorry about my English, it's not my first language.</p>
