2012-09-21 56 views
0

我知道關於callapply在JavaScript中,並且能夠將它們應用於簡單的函數,但當我們將它們應用到鏈式方法調用時,我完全感到困惑,如圖所示下面:導入數組作爲參數鏈接的JavaScript函數

db.collection("posts").find({}, {limit:10, sort:[['views', -1]]}).toArray(function(err, posts) { 
    console.log(posts) 
}); 

是否有可能從數組傳遞參數,像[{}, {limit:10, sort:[['views', -1]]} ]成使用callapply上述方法?

我想用它來輕鬆地訪問&通過保持其在外部陣列修改參數。

謝謝

回答

0

我不認爲有任何方法來保持鏈接。您需要存儲中間結果。

var posts = db.collection("posts"); 
posts 
    .find.apply(posts, argsarray) 
    .toArray(function(err, posts) { 
     console.log(posts) 
    }); 
0

正如你可能知道,這些都是功能等於:

obj.func(1, 2, 3); 
obj.func.apply(obj, [1, 2, 3]); 

考慮到這一點,你可以做到以下幾點:

db.collection("posts").find.apply(
    db.collection("posts") 
    [ {}, {limit:10, sort:[['views', -1]]} ] 
).toArray(...); 

當然,這是非常低效,因爲你會收集兩次。所以,你可以這樣做:

var collection = db.collection("posts"); 
collection.find.apply(
    collection 
    [ {}, {limit:10, sort:[['views', -1]]} ] 
).toArray(...);