Hello there! Today, we're delving into TypeScript classes, focusing on attributes and methods. Attributes define properties, whereas methods define actions. Through the Dog
class, you'll learn these concepts. By the end of the lesson, you should be capable of effectively using attributes and methods in TypeScript classes.
Attributes can be regarded as properties. For a Dog
class, the attributes can include name: "Fido"
, breed: "Poodle"
, color: "White"
. These attributes depict a dog's characteristics, such as those of Fido.
In the Dog
class, we define attributes like name
, breed
, and color
directly. These attributes represent a dog's characteristics and are set with default values:
TypeScript1class Dog { 2 name: string = 'Fido'; 3 breed: string = 'Poodle'; 4 color: string = 'White'; 5}
To instantiate the class and access these attributes, you would do the following:
TypeScript1let fido = new Dog(); 2 3console.log(fido.name); // Prints: Fido 4console.log(fido.breed); // Prints: Poodle 5console.log(fido.color); // Prints: White
Here, Fido is an object of the Dog
class.
Methods are actions that instances of a class can execute. For the Dog
class, behaviors might include bark()
, eat()
, and sleep()
. These methods are functions defined in the class.
Let's enrich Fido's life with some actions. By introducing methods to the Dog
class, we can enable him to bark, eat, and sleep:
TypeScript1class Dog { 2 name: string = 'Fido'; 3 breed: string = 'Poodle'; 4 color: string = 'White'; 5 6 bark() { 7 console.log('Woof Woof!'); 8 } 9 10 eat(food: string) { 11 console.log(`${this.name} is eating ${food}.`); // "this" refers to the current instance of the Dog class, referencing the class attribute. 12 } 13 14 sleep() { 15 console.log('Zzz...'); 16 } 17}
Here, the bark
, eat
, and sleep
methods determine a Dog
object's behavior. Now, an instance of Dog
can bark, eat, and sleep. Note the usage of this
in the eat(food: string)
method - here this
refers to the current instance of the Dog
class, referencing the class attribute.
Let's create an object from the Dog
class and call its methods:
TypeScript1let fido = new Dog(); 2 3console.log(fido.name); // Prints: Fido 4console.log(fido.breed); // Prints: Poodle 5console.log(fido.color); // Prints: White 6 7fido.bark(); // Prints: Woof Woof! 8fido.eat("bone"); // Prints: Fido is eating bone. 9fido.sleep(); // Prints: Zzz...
Equipped with attributes and methods, our Dog
class truly comes alive!
That's about it! With attributes and methods, you can render TypeScript classes more interactive. In this lesson, the Dog
class served to demonstrate the application of attributes and methods. Up next are exercises tailored for you to practice and hone these learned concepts. Happy coding!