JavaScript has a set of built-in methods you can use with your user-defined objects. In this article I’m going to discuss several of these methods and how you can use them in your JavaScript programs.
The Object.assign
method is used to make a copy of one object into another object. The syntax template for this method is:
Object.assign(target, source);
where source is the object you are copying from and target is the object you are copying into. This method returns the target object if you want to assign it.
Here is a sample program that demonstrates how to use Object.assign
:
function Student(name, id, grades) {
this.name = name;
this.id = id;
this.grades = grades;
}
let st1 = new Student("",0,[]);
et st2 = new Student("Jane Doe", 123, [91, 92, 93]);
Object.assign(st1, st2);
print(`${st1.name}, ${st1.id}\n[${st1.grades}]`);
The output from this program is:
Jane Doe, 123
[91, 92, 93]
A good reason to use this method is to make sure that a new object has all the properties and values of the old object. You may accidentally leave something out when writing your own method, while Object.assign
will systematically make sure all properties and values are assigned to the new object.
The Object.create
method creates a new object from an existing object prototype. Here is the syntax template for this method:
const|let|var object-name = Object.create(existing-object);
Let’s look at a few examples to see how this method works in practice. The first example creates a new object from a function and then creates a second object using Object.create
:
function Student(name, id, grades) {
this.name = name;
this.id = id;
this.grades = grades;
}
let st1 = new Student("Bob Green", 1234, [81, 77, 92]);
print(`${st1.name}, ${st1.id}\n${st1.grades}`);
let st2 = Object.create(st1);
print(`${st2.name}, ${st2.id}\n${st2.grades}`);
The output from this program is:
Bob Green, 1234
81,77,92
Bob Green, 1234
81,77,92
Code must be written to change the properties of the newly created object.
#learn-to-code #javascript-development #learn-to-program #javascript #learning-javascript