Definition
“The Object.assign()
method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.” ~ Mozilla Developer Network
There are a million other post talking about what it does so instead I’m just going to dive right into the different ways that Object.assign (JavaScript) method can be used. Also if you’re go to isn’t already https://developer.mozilla.org/ for your JavaScript docs then you should start.
Dynamic Instantiation similar to C#
We all want the C# initializer in JS! So have it.
// the PersonCS class will be used in each example that follows.
class PersonCS{
constructor(initializer = {}){
this.FirstName = null;
this.LastName = null;
this.DOB = null;
this.Height = null;
this.GetFullName = function (){
return `${this.FirstName} ${this.LastName}`
}
Object.assign(this, initializer);
}
}
let person = new PersonCS({
FirstName: "John",
LastName: "Doe",
DOB: new Date("01/23/2019")
})
console.log(person)
Yep that simple: Replace your list of parameters with a variable and provide an empty object as a default value, then at the end of your constructor add use Object Assign to map the values from the initializer variable.
See how this is used in my next post DDNS Client with Node and TypeScript
Object Inheritance
You can inherit using using EcmaScript 6. We don’t always have that luxury. So here’s object inheritance using with a ES5 class
function Teacher(){
Object.assign(this, new PersonCS());
this.TeacherID = 0;
this.PrimarySubject = "English"
}
console.log(new Teacher());
function Student(){
Object.assign(this, new PersonCS());
this.StudentID = 0;
}
console.log(new Student());
Add the Object.assign method at the beginning of your class to effectively inherit the properties of the parent class.
Mapping
So you’re getting back some JSON from an API and you need to map it to your JS Method that has all the juicy Object methods you need for your project. This is more or less what this Object assign is used for.
var response = API.Response();
var models = response.map(element => {
return Object.assign(new PersonCS(), element);
});
console.log(models[0].GetFullName());
// "John Doe" code output
It’s a simple way to change the object received by an API to the class defined in the JS project. Combine the Ojbect.assign with the Array.prototype.map method to have a ‘one-line’ mapping of parsed objects to your desired class.
Full Code: https://github.com/rimendoz86/Recks.pw-MethodOfTheWeek/blob/master/Object.assign/script.js
This looks like alien language, it’s like reading the plans to the Death Star… you’re so smart though.