2012-10-30 26 views
2

我有一個現有的項目(可惜)使用underscore.js而不是ES5墊片來支持IE8和其他非ES5瀏覽器。我習慣於ES5,但通常不使用下劃線。我已閱讀underscore documentation on _.bind並試圖使其正常工作。如何將此工作原生ES5代碼轉換爲使用下劃線的_.bind()?

下面是使用原生ES5一個工作示例:

// Greets people 
HelloThing = function (greeting) { 
    this.greeting = greeting; 

    this.waitAndSayHello = function() { 
     setTimeout(function() { 
      console.log(this.greeting) 
     }.bind(this), 500); 
    } 
} 


var pretend_thing = new HelloThing('hello world'); 
pretend_thing.waitAndSayHello(); 

下面是使用我的文檔的理解強調一個失敗的嘗試:

// Greets people 
HelloThing = function (greeting) { 
    this.greeting = greeting; 

    this.waitAndSayHello = function() { 
     var greet = function() { 
      alert(this.greeting) 
     } 
     _.bind(greet, this) 
     setTimeout(greet, 500); 
    } 
} 


var pretend_thing = new HelloThing('hello world'); 
pretend_thing.waitAndSayHello();​ 

我怎樣才能讓下劃線的工作?

回答

3

_.bind()方法返回綁定函數。你不會對返回的函數做任何事情。將其分配到的東西,並使用該引用而不是原來的greet參考:

var greet = function() { 
    alert(this.greeting) 
}; 
greet = _.bind(greet, this); 
setTimeout(greet, 500); 

如果您拓展ES5例子,你會看到,這是有效的是與本地bind方法發生了 - 你可以直接調用在功能對象上,因爲它屬於Function.prototype

var greet = function() { 
    alert(this.greeting); 
}; 
greet = greet.bind(this); 
setTimeout(greet, 500); 
+0

謝謝James,非常感謝。 – mikemaccana

相關問題