2015-05-04 17 views
0

有人可以解釋我爲什麼這個函數變得未定義時,我把它存儲在一個變量?爲什麼這個函數表達式不確定?

model.where({'artisan.id':id}).count(function(err, doc) { 
    console.log(err, doc); // this work 
}) 

var fn = model.where({'artisan.id':id}).count; 

console.log(typeof fn); // ==> 'function' 

fn(function(err, doc) { // undefined is not a function 
     console.log(err, doc); 
}) 

謝謝。

+0

@AlfonsoGarnett,如果這是真的,那麼他們的typeof新生力量的console.log將顯示爲未定義,他們的第一線將不能工作。亞伯,你確定這是錯誤引用的實際行嗎? –

+0

當我用10秒的超時時間調用fn時,它仍然是未定義的。看起來它是未定義的回調函數。但它沒有任何敏感...... –

+0

'count'可能期望'this'的值引用特定對象,而不是全局對象。一般來說'var foo = obj.foo; foo();'不等於'obj.foo()'。 –

回答

0

的錯誤可能是因爲你沒有實際調用count()的方法需要一些內部屬性。

指定.countfn僅保留對function本身的引用。它將從model.where({'artisan.id':id})查詢對象中分離出來,並且稍後將使用默認的this值 - globalundefined進行調用,具體取決於嚴格模式的使用情況。

在某些時候,它可能會試圖引用的另一種方法,該不會是可通過默認this,如:

function count(callback) { 
    this.method(...);  // TypeError: undefined is not a function 
    // global.method(...); 
} 

一種方式來解決這是.bind()的方法,所以它this值迷戀:

var query = model.where({'artisan.id':id}); 
var fn = query.count.bind(query); 

fn(function (...) { ... }); 
1

我認爲錯誤不是從您所說的行中拋出,而是從fn函數內部拋出,因爲您正在使用錯誤的上下文執行它。

當你說model.where(...).count(...)使用來自where()返回其上下文值執行計數功能,但是當你fn(...)未發生而不是函數將使用(在嚴格模式undefined)的window上下文中執行它可能無法找到導致錯誤

var where = model.where({ 
    'artisan.id': id 
}); 

var fn = where.count; 

console.log(typeof fn); // ==> 'function' 

fn.call(where, function (err, doc) { // undefined is not a function 
    console.log(err, doc); 
}) 
//or 
where.count(function (err, doc) { 
    console.log(err, doc); // this work 
}) 
相關問題