J090 Object Usage
A dive into creating and manipulating objects using different syntax in JavaScript.
In your app.js:
Task:
- Create three objects (
o1,o2, ando3). All objects should have two properties:firstNameandlastName, both with values “a” and “b”. - Add a method named
fullName()to each object. This method should return the combinedfirstNameandlastNamewith a space in between. - Remember that the
thiskeyword can be used to access object properties (but not inside arrow functions). - The first object should be created using the
[]syntax, the second using the.syntax, and the third using the{}syntax. - Test the objects by printing the return values of the methods.
Solution
"use strict";
// 1. Object creation using [] syntax
let o1 = new Object();
o1['firstName'] = 'a';
o1['lastName'] = 'b';
o1.fullName = function() {
return this.firstName + ' ' + this.lastName;
}
// 2. Object creation using . syntax
let o2 = new Object();
o2.firstName = 'a';
o2.lastName = 'b';
o2.fullName = function() {
return this.firstName + ' ' + this.lastName;
}
// 3. Object creation using {} syntax
let o3 = {
firstName: 'a',
lastName: 'b',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
}
// Test objects by printing the full names
console.log(o1.fullName());
console.log(o2.fullName());
console.log(o3.fullName());
This exercise provides learners with an understanding of different methods to declare and instantiate objects in JavaScript.