![](/img/trans.png)
[英]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.