2009-01-08 30 views
0

我有這樣一段代碼:String.replace;通過函數的結果問題更換

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.對不起,我的英語不是我的第一語言。

+0

您的代碼是沒有意義的! 「解析」是否意味着一個功能? – James 2009-01-08 17:09:24

回答

4

也許嘗試:

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

這是:-)最有用的技巧之一

UPDATE:訣竅是不是我的,我學到了(因爲大部分的東西我知道Javascript)來自:Douglas Crockford

+0

這個「那個」確實解決了這個問題。 :o)我儘量避免使用輔助變量。但我從你的回答中瞭解到,這種方法被認爲是這種情況下的「標準」解決方案。謝謝! – Dero 2009-01-08 16:34:20

0

爲此聲明一個變量。

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

這就是原型和其他人做的

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