tags:

views:

240

answers:

3

Hi,

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 do the trick, because I'm in the scope of the anonymous function. I can't re-scope the anonymous function using .call(this) statement either, because in th ta case I would lose the parameters passed to the function by String.replace.

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

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

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

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

... which suffers from serious performance issues. Any ideas would be greatly appreciated.

-- D.

P. S. Sorry about my English, it's not my first language.

A: 

declare a variable for that.

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

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

It is one of the most useful tricks :-)

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

rkj
This "that" sure solves the problem. :o) I try to avoid assistive variables wherever possible. But I understand from your answer, that this approach is considered as a "standard" solution for this kind of situations. Thanks!
Dero
+1  A: 

This is what prototype and others do

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