I want to use ionic sample app to build a web app. There is a part of sample code written in typescript. I cannot understand meaning of code of this[f] = fields[f] Could you please explain what is the meaning of this code?
The full code of this ts file is:
/**
* 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;
}
You're looking at a dynamic property accessor. Say "fields" was {first: 1, second: 2}
, the code would be the equivalent of:
this.first = fields.first this.second = fields.second
So in short, it assigns all the enumerable properties of fields into this.
Think of it as a generic constructor. What it does is iterate the members of an object aliased "fields" in the function's scope and assigns the values to "this" which is the object getting created. For example, if the object passed was :
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
}
This is bracket notation for property access. You can learn more on MDN here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.