2015-04-04 70 views
1

當我將函數傳遞給貓鼬時,它似乎不再有對this的引用。有沒有更好的方法來解決這個問題?所有功能都因爲長度原因而被簡化。我無法編輯功能getUsernameForId以獲取其他參數。貓鼬傳遞類函數

我有類:

var class = new function() { 

    this.func1 = function(data) { 
     return data + "test"; 
    } 

    this.func2 = function(data) { 
     var next = function(username) { 
      return this.func1(username); // THIS THROWS undefined is not a function 
     } 
     mongoose.getUsernameForId(1, func3); 
    } 

} 

貓鼬另一類是這樣的:

var getUsernameForId = function(id, callback) { 
    user_model.findOne({"id": id}, function(err, user) { 
     if(err) { 
      throw err; 
     } 
     callback(user.username); 
    }); 
} 

如何解決undefined is not a function error。我不想複製代碼,因爲func1在現實中很長。

回答

1

這不是從你的代碼清楚如何next被使用,但如果你需要用它來正確this被調用,你可以嘗試使用Function.prototype.bind方法:

this.func2 = function(data) { 

    var next = function(username) { 
     return this.func1(username); 
    }.bind(this); 

    mongoose.getUsernameForId(1, func3); 
} 

我假設你的職位簡化代碼而next在現實中做了更多的事情。但是,如果它確實只是返回的結果this.func1那麼你可以縮短它:

var next = this.func1.bind(this); 
+0

新來JS和不知道這個功能的。在一分鐘內接受。這是一個常用的約定嗎? – jn1kk 2015-04-04 21:23:18

+0

是的,現在綁定是非常方便和普遍的,並且允許很好的語法。 – dfsq 2015-04-04 21:29:16