我想使用离子样品应用程序来构建Web应用程序。有一部分示例代码是用打字稿编写的。我不明白的代码的含义 这个[f] =字段[f] 您能否解释一下此代码的含义?
此ts文件的完整代码为:
/**
* A generic model that our Master-Detail pages list, create, and delete.
*
* Change "Item" to the noun your app will use. For example, a "Contact," or
a
* "Customer," or a "Animal," or something like that.
*
* The Items service manages creating instances of Item, so go ahead and
rename
* that something that fits your app as well.
*/
export class Item {
constructor(fields: any) {
// Quick and dirty extend/assign fields to this model
for (const f in fields) {
// @ts-ignore
this[f] = fields[f];
}
}
}
export interface Item {
[prop: string]: any;
}
答案 0 :(得分:1)
您正在查看动态属性访问器。假设“字段”为{first: 1, second: 2}
,则代码等同于:
this.first = fields.first
this.second = fields.second
因此,简而言之,它会将字段的所有可枚举属性分配给它。
答案 1 :(得分:1)
将其视为通用构造函数。 它的作用是在函数范围内迭代别名为“字段”的对象的成员,并将值分配给要创建的对象“ this”。 例如,如果传递的对象是:
var fields= {mem1: 1, mem2: 'marios'};
the code would then
for (const f in fields) {
this[f] = fields[f];
// 1st iteration would be
// this[mem1] = fields[mem1]; -> this[mem1] will create the property to the new object
// fields[mem1] will read the value, so it created the prop and copies the value
}
答案 2 :(得分:1)
这是属性访问的括号符号。您可以了解有关MDN here
的更多信息