Creating and Accessing Properties
Key/value pairs are called object properties and are separated by commas. If we take the example of a Person object, the properties of the object could look like this:
var Person = {
firstName: "John",
lastName: "Doe",
birthYear: 1978
};
The Person in the above example is an object with properties firstName, lastName, and birthYear. These properties are accessed using dot notation (person.firstName) or bracket notation (person["lastName"]).
To access a specific property within an object, you can do it as follows:
ObjectName.propertyName;
If you wanted to access the firstName property from the Person object example, you would do it in one of two ways:
Person.firstName; Person["lastName"];
Functions in Objects
It is also possible to write functions as properties of an object. Object functions are known as object methods. In the example below, the Person object is extended with a method for returning the full name.
var Person = {
firstName: "John",
lastName: "Doe",
birthYear: 1978,
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
To call the fullName function, you can do it as follows.
Person.fullName(); var fullName = Person.fullName();
If you leave out the parentheses “()” when calling the function, the function definition will be returned.
Iterating Over Object Properties
You can loop through each key-value pair in an object using a for...in loop. We will discuss loops in the next lessons.
for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(key + ": " + person[key]);
}
}
The for...in loop iterates over each property in the person object, printing the property name and its value.
Nested Objects
Objects can contain other objects, enabling the construction of complex data structures.
let person = {
name: {
first: "John",
last: "Doe"
},
age: 30
};
console.log(person.name.first); // "John"
The person has a name object as a property, which in turn has first and last properties.
Object Inheritance
JavaScript objects are prototypical, meaning they can inherit properties and methods from other objects.
let employee = Object.create(person); employee.job = "Developer"; console.log(employee.job); // "Developer" console.log(employee.name.first); // "John" - inherited from person
The employee object is created as a new object that inherits from person. It has its own property job, and also access to properties of person.
Object Constructors
A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
What is this?
In JavaScript, the this keyword refers to an object. Which object it refers to depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
- In an object method, this refers to the object.
- Alone, this refers to the global object.
- In a function, this refers to the global object.
- In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Working with objects
In the following example, the user is asked to enter the name and surname of a person. The Person is created as an object that contains properties; name, surname, and a function that returns the full name. When the user enters the name and surname, the Person object is filled and the values are displayed using the alert(); function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JS - Working with objects</title>
<script>
function Person(name, surname) {
this.name = name;
this.surname = surname;
this.fullName = function () {
return this.name + " " + this.surname;
}
}
function runApp() {
// Regular binding to properties
var p = new Person();
p.name = prompt("Enter the person's name:", "");
p.surname = prompt("Enter the person's surname:", "");
// Using the constructor
// var person = new Person(
// prompt("Enter the person's first name:", ""),
// prompt("Enter the person's last name:", ""));
alert("Entered person: " + p.fullName());
}
</script>
</head>
<body>
<h1>JS Work with objects</h1>
<a href="#" onclick="runApp()">RUN APP</a>
</body>
</html>