2016-05-13 65 views
-1

我寫貓鼬中間件,像這樣的λ,使用ES6:匿名函數VS在貓鼬

userSchema.pre('save', (next) => { 
    // something... 
    next(); 
}); 

並沒有奏效。中間件被調用,但「this」沒有引用正在保存的文檔。然後我擺脫了lambda語法:

userSchema.pre('save', function(next) { 
    // something... 
    next(); 
}); 

它的工作!

我一直很開心地使用帶有Node的lambdas一段時間,有沒有人知道問題是什麼? (我已經看到這裏有一個關於這個問題的question,不過,我希望有一個基本的答案)。

+0

lambda是一個匿名函數 - 一個沒有名字的函數。你的兩個例子都是lambda表達式。但是,箭頭函數具有詞彙「this'。 – naomik

回答

2

是的,這是預期的行爲,則使用箭頭函數時,這個捕捉到封閉的上下文的值,以使得:以下更多信息

function Person(){ 
    this.age = 0; 

    setInterval(() => { 
    this.age++; // |this| properly refers to the person object 
    }, 1000); 
} 

var p = new Person(); 

參見詞法本節中的MDN頁: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this

這是偉大的,因爲以前我們不得不這樣寫代碼:

function Person() { 
    var self = this; // Some choose `that` instead of `self`. 
        // Choose one and be consistent. 
    self.age = 0; 

    setInterval(function growUp() { 
    // The callback refers to the `self` variable of which 
    // the value is the expected object. 
    self.age++; 
    }, 1000); 
} 

共de樣品直接從MDN文章中獲取。