2016-01-19 150 views
0

我創建了一個功能來查找對象:爲什麼下面的_.map函數什麼都不返回?

store.js

store.find =() => { 
    const query = new Parse.Query(Document) 
    return query.find() 
} 

,我使用這樣的(和分配價值this.documents):

main.js

store.find().then((results) => { 
    this.documents = _.map(results, (result) => { 
    return result.toJSON() 
    }) 
}) 

它的工作原理。但store.find().then(...)部分在main.js重複很多次,所以我把它變成一個功能:

store.js

store.fetch = (documents) => { 
    return store.find().then((results) => { 
    documents = _.map(results, (result) => { 
     return result.toJSON() 
    }) 

    }) 
} 

,我用這樣的:

main.js

store.fetch(this.documents) 

但是沒有東西被分配給this.documents並且沒有錯誤消息。可能是什麼問題?

注意:this.documents是一個對象數組。例如:

[{ 
    title: this.title, 
    content: this.content, 
}, ... 

編輯:

我這樣做:

store.fetch = (documents) => { 
    store.find().then((results) => { 
    documents = _.map(results, (result) => { 
     return result.toJSON() 
    }) 
    console.log(documents) 
    }) 
} 

而且documents被分配:

[Object, Object, Object, ...] 

所以我認爲它只是不分配這個數組到this.documents。也許變量不能是參數,並且可以同時賦值?

+3

嘛,你不* *返回任何東西,你只是分配給'documents'。 – deceze

回答

2

你傳入this.documents作爲參數,並試圖修改函數內部的財產。但是,這是行不通的,因爲Javascript does not have "pass by reference"。只有「按價值傳遞」。

相反,你可以嘗試分別傳遞對象和屬性名:

store.fetch = (obj, prop) => { 
    return store.find().then((results) => { 
    obj[prop] = _.map(results, (result) => { 
     return result.toJSON() 
    }) 
    }) 
} 
store.fetch(this, 'documents') 
+0

嘿,它的工作。這太奇怪了,我會檢查你發佈的鏈接。非常感謝! – alexchenco

+0

我仍然不明白爲什麼'this'和'documents'一起傳遞時它不起作用,但是當它們分開傳遞時它們會執行。 – alexchenco

+1

@alexchenco爲了分配一個屬性,你需要對象和屬性名稱。您試圖傳遞該屬性,但只將其值傳遞給該函數,而不是您希望它屬於的對象。 – Oriol

1

嘗試在store.fetch(this.documents)後得到.then塊中的結果。而且不要忘記存儲方面

var self = this; 
store.fetch(self.documents).then(function() { 
    console.log(self.documents); 
}); 

或者usign ES6

store.fetch(this.documents).then(() => { 
    console.log(this.documents); 
});