简体   繁体   中英

convert an object to a class instance

I have a javascript app that reads a json file on the server; the function that reads the json file returns an object.

Until now I was using that object (it represents an album of photos) in the app, but now I want to make it an instance of a class, so that I'm going to manipulate it through the class methods.

Surely I'm doing something like:

var album = new Album(object);

My question is: what is the best way to generate the class properties in the constructor? can I iterate on the object properties with something like:

Object.keys(object).forEach(function(key) {
  this[key] = object.key;
}

or should I assign manually each object property to the corresponding class property?

In this case, I'm going to say best is a matter of opinion. What you are doing will work and is clean and simple but it should fail due to this and the function reference also due to the missing ) .

The following version should work for you.

Object.keys(object).forEach((key) => {
  this[key] = object[key];
})

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM