String.replace; replace with function result result

I have this piece of 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); } );
   }
}

      

Of course, calling this.complex ($ 1) won't help, because I'm entering the scope of an anonymous function. I cannot reuse the anonymous function using the .call (this) operator because in that case I would lose the parameters passed to the String.replace function.

So far, I am using a specific instance of an object. This is my decision:

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

      

This is sufficient for my needs so far, but I'm wondering if there is any one-size-fits-all solution for this problem. The only idea that has worked for me so far is this:

function ($1) { return (new myObj).complex($1); }

      

... that suffers from serious performance problems. Any ideas would be greatly appreciated.

- D.

RS Sorry for my English, this is not my first language.

0


source to share


3 answers


Maybe try:

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

      



This is one of the most useful tricks :-)

UPDATE: The trick is not mine, I learned it (as do most things I know about Javascript): Douglas Crockford

+4


source


This is what prototype and others are doing

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

      



Now you can do this

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

      

+2


source


declare a variable for this.

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

      

0


source







All Articles