Conteúdo do curso
JavaScript Course for Beginners: Fundamentals and Practice
Sobre a Aula

Properties and Methods of Objects

Congratulations on reaching the last lesson of Module 5! In this final stage, you will become a master of properties and methods of objects in JavaScript, exploring advanced features to manipulate data even more efficiently and flexibly.

Accessing and Modifying Properties

In the previous topic, we touched on this subject, but here we will delve a bit deeper with a different example. So, let’s start with an analogy:

Imagine an object as a box containing different items.

Each item is a property, and each property has a name and a value.

To access or modify a property in JavaScript, we can use dot notation (.) or bracket notation ([]).

Using the box analogy, we can think of dot notation as opening the box and grabbing an item directly by its name.

For example, if we have an object called “person” with the property “name,” we can access the value of this property as follows:

let person = {
  name: "John",
  age: 25
};

console.log(person.name); // Output: "John"

Similarly, we can modify the value of a property using dot notation:

person.age = 30;
console.log(person.age); // Output: 30

Bracket notation is like using a label to get a specific item inside the box.

Instead of using the name directly, we use a string representing the property name. See the example below:

console.log(person['name']); // Output: "John"

This notation is useful when the property name is dynamic or contains special characters. We can also use variables to access properties:

let propertyName = 'age';
console.log(person[propertyName]); // Output: 30

Through these ways of accessing and modifying properties, we can work with the data contained in JavaScript objects.

It is essential to practice and understand how to use dot notation and brackets correctly to interact with the properties of an object.

Remember that accessing and modifying properties are fundamental to manipulating and working with objects in JavaScript.

With practice and experience, you will be able to use these techniques efficiently in your projects.

Calling Methods

When working with objects in JavaScript, in addition to properties, we can also have methods. Methods are actions or behaviors associated with an object.

We can think of them as special instructions that an object can execute.

Let’s use an analogy to better understand. Imagine an object called “car” that has various properties, such as “color,” “brand,” and “model.”

In addition, it also has methods, such as “start” and “stop.”

When calling a method in JavaScript, we are asking the object to perform a specific action.

We can do this using dot notation (.) or bracket notation ([]), just as we saw earlier to access properties.

Using the car analogy, we can think of calling a method as pressing a button on the car’s dashboard to perform a specific action.

For example, we can call the “start” method of the “car” object as follows:

car.start();

This method call instructs the “car” object to perform the action of starting. Similarly, we can call the “stop” method:

car.stop();

Like properties, methods can also receive arguments.

These arguments are additional information that we can pass to the method, allowing it to perform the action in a customized way.

For example, we can have a method called “accelerate” that receives the desired speed as an argument:

car.accelerate(80);

In this case, we are instructing the “car” object to accelerate to a speed of 80 km/h.

When calling methods, we are activating specific behaviors of the object. This allows our objects to perform useful actions and interact with the rest of the code.

Therefore, remember that methods are actions associated with an object and can be called using dot notation.

Additionally, methods can receive arguments, allowing you to customize their actions as needed.

With practice and understanding of these concepts, you can create JavaScript objects that perform complex tasks and interact with your code powerfully.

Using the ‘this’ Operator

In JavaScript, the ‘this’ operator is used to refer to the current object, i.e., the object we are currently working with.

It is quite useful when we want to access properties or methods within the object itself.

Let’s use an analogy to better understand. Imagine an object called “person” that has various properties, such as name and age.

Now, suppose we want to create a method inside this object called “introduce,” which prints a message on the screen with the person’s name.

Within the “introduce” method, we can use the ‘this’ operator to reference the person object itself.

It’s like ‘this’ is a mirror that reflects the current object we are working on.

So, the “introduce” function would look like this:

const person = {
  name: "John",
  age: 25,
  introduce: function() {
    console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
  }
};

Here, we are using the ‘this’ operator to access the name and age properties of the person object.

This way, when we call the “introduce” method, it will print a personalized message with the name and age of the current person.

The ‘this’ operator allows our code to be more dynamic as it adapts to the current object we are working with.

It’s like creating a template that can be filled with the specific values of each object.

Therefore, the ‘this’ operator is used to reference the current object and allows you to access its properties and methods within the object itself.

It brings important flexibility to working with objects in JavaScript, enabling you to create reusable and adaptable code for different instances of the object.

Inheritance and Prototypes

In JavaScript, inheritance and prototypes are concepts that allow us to create objects that inherit properties and methods from other objects.

We can think of inheritance as a process where a more specific object can acquire characteristics from a more generic object, becoming an extension of it.

Let’s use an analogy to better understand. Imagine that we have a template for a car called CarTemplate.

This template contains all the common features of all cars, such as wheels, steering wheel, and engine. Now, we can create several cars from this template, such as Car1, Car2, and so on.

These created cars will inherit the characteristics of the template but can also have specific features added later.

In JavaScript, we can create objects using a constructor function that acts as our template, defining common properties and methods.

Then, we can create new objects from this constructor function using the ‘new’ keyword. These created objects will inherit the properties and methods of the constructor function.

Moreover, in JavaScript, each object has a prototype, which is a reference to another object.

This prototype contains properties and methods that can be accessed by the object.

If a property or method is not found in the object itself, JavaScript will look in the prototype, and if not found there, it will continue searching in the higher prototypes until it reaches the Object object at the top of the prototype chain.

This prototype chain allows the inheritance of properties and methods between objects.

When we try to access a property or method on an object, JavaScript first checks if it exists in the object itself. If

not, it looks in the prototype and throughout the prototype chain.

This gives us flexibility to create objects that share common characteristics while also allowing us to add specific properties and methods for each individual object.

Now, let’s create a simple example to illustrate the concept of inheritance and prototypes in JavaScript.

// Constructor function for the Car object
function Car(brand, model) {
  this.brand = brand;
  this.model = model;
}

// Adding a method to the prototype of the Car object
Car.prototype.getDescription = function() {
  return this.brand + " " + this.model;
};

// Creating an object from the Car constructor function
var myCar = new Car("Ford", "Mustang");

// Accessing properties and methods of the myCar object
console.log(myCar.brand); // Ford
console.log(myCar.model); // Mustang
console.log(myCar.getDescription()); // Ford Mustang

In this example, we have the Car constructor function that defines the brand and model properties. Then, we add a getDescription method to the prototype of the Car object, which returns the description of the car’s brand and model.

By creating an object myCar using new Car("Ford", "Mustang"), the myCar object inherits the properties and methods of the Car constructor function.

We can access the brand and model properties directly on the myCar object and call the getDescription method to get the car’s description.

This example demonstrates how we can create objects in JavaScript using inheritance and prototypes, allowing code reuse and extension of properties and methods in specific objects.

Therefore, inheritance and prototypes in JavaScript enable us to create objects that inherit properties and methods from other objects, providing an efficient way to reuse and extend code.

It’s like building a hierarchy of objects, where child objects can inherit characteristics from parent objects, resulting in more organized and modular code.

Manipulating Internal Objects

When dealing with objects in JavaScript, it is common to encounter properties that are also objects.

These internal objects can be accessed and manipulated in the same way as any other property of an object.

Let’s use an analogy to better understand. Imagine that an object is like a box containing several other boxes inside it.

Each of these internal boxes is a property of the object and can contain its own set of information.

To access an internal property of an object, it’s no different from what we’ve seen before; we can use dot notation (.) or brackets ([]).

For example, considering the person object with the internal address property, we can access this property as follows:

var person = {
  name: "John",
  age: 25,
  address: {
    street: "Main Street",
    number: 123,
    city: "São Paulo"
  }
};

console.log(person.address.street); // "Main Street"
console.log(person["address"]["city"]); // "São Paulo"

In this example, the person object has the address property, which is another object with the properties street, number, and city.

To access the street, we can use dot notation after the address property (person.address.street), or we can use brackets and pass the property name as a string (person["address"]["street"]).

Similarly, we can modify the values of internal properties. For example, we can change the city of the person as follows:

person.address.city = "Rio de Janeiro";
console.log(person.address.city); // "Rio de Janeiro"

This way, we can manipulate internal objects, accessing and modifying their properties in the same way we would with any other property of an object.

Understanding this manipulation of internal objects is important because it allows working with more complex and nested data structures in JavaScript, enabling the creation of objects that more faithfully represent real-world entities.

Now that you have mastered string manipulation methods, understood the concept of objects in JavaScript, and explored the properties and methods of these objects, it’s time to test your skills with a practical challenge.

Challenge:

Create a JavaScript script that creates an object to represent a book, with properties such as title, author, publication year, and number of pages.

Add a method to the object that calculates the average reading time, considering 200 pages per hour.

Use the method to calculate the reading time of the book and display the result on the screen.

Congratulations on completing the module! You now have a solid foundation to create more complex and interactive programs, manipulating data efficiently and organized.

When you’re ready, move on to the next module. I’ll see you there!

Entrar na conversa
Rolar para cima