[英]How do I create multiple instances of a object in javascript during runtime?
[英]How do I access a property that I added during runtime to an object?
在這個例子中,我向對象添加了屬性“col_id_3”。 后來我想訪問它。 盡管我可以看到屬性“col_id_3”在那里(見圖),但我無法使用Object.col_id_3
訪問它。 JavaScript 返回undefined
。 我該如何訪問它? 如何使該屬性“粘”到對象上?
myFunction: function(){
return db.allDocs({include_docs: true}, function(err, response) {
var myArray =[];
if(err) {
console.log(err);
throw new Error(console.error("error"));
} else {
return Promise.all(response.rows.map(function(row){
if(row.doc.type == 'myAttribute') {
row.myNewlyAddedProperty = {id: row.doc._id,
name: row.doc.data.name,
isValid: false
};
myAsynchFunction(row.qc)
.then(anotherAsynchFunction(row.qc), function(error) {
console.error("handle error: "+error.stack);
throw error;
})
.catch(function(error) {
console.error("handle error in catch case: "+error.stack);
});
}
}));
}
})
.then(function (arrayResults) {
var onlyFilteredResults = [];
for (var i = 0; i < arrayResults.rows.length; i++){
var changedInput = arrayResults.rows[i];
if (arrayResults.rows[i].doc.type == 'myAttribute') {
console.log(changedInput); // here I can see my newly add Attribute
console.log(changedInput.myNewlyAddedProperty); // here I can't access my newly attribute anymore
console.log(Object.keys(changedInput)); //here my newly added Attribute isn't listed
}
console.log
顯示對象在擴展時的狀態,而不是在日志時。 因此, changedInput
有myNewlyAddedProperty
當時您單擊展開記錄的對象,而不是當你真正做了log
通話。
您的問題是您同時使用了db.allDocs
的回調和承諾。 假設您在這里使用 PouchDB,在回調運行之前承諾結果:
db.allDocs({}, function() { console.log("callback"); })
.then(function() { console.log("promise") })
此代碼將首先記錄"promise"
,然后記錄"callback"
。 因此,您的.then(function (arrayResults) { ... })
在db.allDocs(..., function(err, response) { ... })
回調之前運行。 這里的解決方案是不要對allDocs
使用回調, allDocs
使用承諾:
db.allDocs(...)
.then(function(response) {
var myArray =[];
...
return response;
})
.then(function (arrayResults) {
var onlyFilteredResults = [];
...
});
此外,您的response.rows.map
回調不返回任何值,因此Promise.all
獲取undefined
值的數組。 我假設您想return myAsynchFunction(row.qc).then(...)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.