从函数访问公共属性的最佳方法是什么?
我有一个场景,当一个函数执行时,它应该更新一个对象/数组的公共属性。
以下是我的代码:
TS文件
formName = "support";
formTemplate = {
"types": [
"text",
"file",
"number",
"email"
],
"support": {
"description": "This will generate form for support request",
"fields": [
{
"name": "title",
"element": "input",
"type": "text",
"label": "Title",
"placeHolder": "Provide Short Discription",
"classes": "form-control",
"value": ""
},
{
"name": "description",
"element": "input",
"type": "text",
"label": "Description",
"placeHolder": "Provide Discription",
"classes": "form-control",
"value": ""
},
{
"name": "email",
"element": "input",
"type": "text",
"label": "Email",
"placeHolder": "Provide email addresses",
"classes": "form-control",
"value": ""
},
{
"name": "attachment",
"element": "file-picker",
"type": "file",
"label": "Attachment",
"placeHolder": "Insert Attachment",
"classes": "form-control",
"value": "test"
}
]
}
};
public processForm(data) {
this.formTemplate.support.fields.forEach(function (item, i) {
if (item.element === 'file-picker') {
// THIS DOESN'T WORK. NEED TO ACCESS formTemplate and update value for a property
console.log(this.formTemplate.support.fields[i].value);
}
});
}
因此,当从点击视图执行processForm
时,它应该能够访问formTemplate
对象。由于this
在函数中是本地的,因此需要帮助访问函数范围之外的formTemplate
。
非常感谢任何帮助。 :)