2010-08-25 80 views
8

在我的JavaScript對象,我發現自己寫的:有沒有比設置變量更好的方法?

this_object = this; 

這似乎是通過成員變量對外部函數的唯一途徑...

google.maps.event.addListener(this.marker, 'click', function() { 
    this.info_window.setContent('Chicago marker'); 
    this.info_window.open(this.map,this.marker); 
}); 

那是不行的,我有將對象複製到成員變量中並傳遞新對象(並用this_object替換全部this

這樣感覺很難看。有沒有「更好」或「更清潔」的方式,還是這是我唯一的選擇?

+0

另請參見:['this'對象無法在沒有黑客的私人JavaScript函數中訪問?](http://stackoverflow.com/questions/3274387/this-object-cant-be-accessed-in- private-javascript-functions-without-a-hack) – CMS 2010-08-26 00:31:22

回答

5

當然有更好的方法。它涉及創建一個功能,其中this上下文已經綁定到特定的對象。

要讓this上下文引用當前對象,請在該函數上調用bind()方法,並將所需的上下文作爲參數傳遞。

google.maps.event.addListener(this.marker, 'click', function() { 
    this.info_window.setContent('Chicago marker'); 
    this.info_window.open(this.map,this.marker); 
}.bind(this)); // <-- notice we're calling bind() on the function itself 

這是現在ECMAScript標準的一部分,如果瀏覽器沒有實現它本身,它很容易做自己。

if (!Function.prototype.bind) { 
    Function.prototype.bind = function() { 
     var fn = this, 
      args = Array.prototype.slice.call(arguments), 
      object = args.shift(); 

     return function() { 
      return fn.apply(
       object, args.concat(Array.prototype.slice.call(arguments)) 
      ); 
     }; 
    }; 
} 

查看所有與此相關的questions and answers

+0

這看起來像它在我的javascript paygrade上方的一對凹槽,但我會嘗試吸收它。謝謝 – Galen 2010-08-26 01:30:14

+0

這確實有引入額外函數調用的缺點,但是+1。 – 2010-08-26 08:46:26

4

當處理JavaScript以將this的引用存儲在局部變量中時,它實際上是一種非常常見的模式,即var myThing=this;。記住函數可以訪問在其作用域中定義的局部變量。在包含函數中定義的任何變量都是可訪問的。

0

我已經看到之前的模式(被調用的問題變量),所以我認爲它確實是一個常見的JavaScript模式,不僅有一個更乾淨的解決方案。

0

我不確定這將有助於您處理的任何情況,但是我發現YUI的自定義事件實用程序可以很好地處理與此關閉有關的範圍問題。這是一種事件驅動的模式,思維方式略有不同,但至少應該值得探討。

http://developer.yahoo.com/yui/event/#customevent

1

你會發現這段代碼在很多庫和項目相當頻繁:

function someFunction() { 
    var that = this; 

    //.... 
} 

例如,考慮這個功能:

function container(param) { 

    function dec() { 
     if (secret > 0) { 
      secret -= 1; 
      return true; 
     } else { 
      return false; 
     } 
    } 

    this.member = param; 
    var secret = 3; 
    var that = this; 

    return function() { 
     if (dec()) { 
      return that.member + " " + secret; 
     } else { 
      return null; 
     } 
    }; 
} 

var c = container("foo"); 
alert(c()); // "foo 2"; 
alert(c()); // "foo 1"; 
alert(c()); // "foo 0"; 
alert(c()); // null; 

更多here

相關問題