JavaScript objects are containers for named values.
An object has a list of values that are written as name:value pairs, with the names and the values separated by colons.
We use curly braces {} to create an object:
let car = {
color: 'blue';
brand: 'Honda';
};
Spaces and line breaks are not important. An object definition can span multiple lines.
You can access, add or edit a property within an object by using dot notation or bracket notation.
We must use bracket notation when accessing keys that have numbers, spaces, or special characters in them.
objectName.propertyName
//or
objectName['propertyName']
To create a number of objects of a single type, we use an object constructor function.
function person(name, age, color) {
this.name = name;
this.age = age;
this.color = color;
}
Note:
The this keyword refers to the current object. Avoid using arrow functions when using this in a method!
Once you have an object constructor, you can use the new
keyword to create new objects of the same type.
var p1 = new person("Anna", 18, "green");
var p2 = new person("Joe", 21, "blue");
document.write(p1.age); // Outputs 18
document.write(p2.name); // Outputs "Joe"
Methods are functions that are stored as object properties.
To create an object method, we use the following syntax :
methodName = function() { code lines }
TO ccess an object method, we use the following syntax:
objectName.methodName()
function person(name, age) {
this.name= name;
this.age = age;
this.changeName = function (name) {
this.name = name;
this.yearOfBirth = bornYear;
}
function bornYear() {
return 2020 - this.age;
}
var student = new person("Anna", 21);
student.changeName("Hanna");
// Now student.name = "Hanna"
console.log(sudent.yearOfBirth());
// Outputs 1999
Getter methods get and return the internal properties of an object
Setter methods reassign values of existing properties within an object.
This method is used to copy one or more source objects to a target object.
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
We use the Object.keys() method to return all the keys (Javascript objects are written as “key: value” pairs).
const object1 = {
a: 'hello',
b: 'hi',
c: 24
};
console.log(Object.keys(object1));
// Output: ["a", "b", "c"]
Read more on MDN’s object instance documentation.