mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-06-19 21:09:51 +08:00
feat(curriculum): update class lesson with interactive example (#63572)
This commit is contained in:
parent
1bacf09dd5
commit
ec86ed5212
@ -5,9 +5,7 @@ challengeType: 19
|
||||
dashedName: what-are-classes-and-how-do-they-work-in-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Let's learn about classes in JavaScript.
|
||||
# --interactive--
|
||||
|
||||
In modern JavaScript, classes are like blueprints that you can define in code for creating multiple objects of the same kind.
|
||||
|
||||
@ -81,24 +79,54 @@ You can then access this property using the dot notation, like you can see in th
|
||||
console.log(dog.name);
|
||||
```
|
||||
|
||||
This will log the value of the `name` property of this particular instance:
|
||||
Here is the full example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
Gino
|
||||
class Dog {
|
||||
constructor(name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
bark() {
|
||||
console.log(`${this.name} says woof!`);
|
||||
}
|
||||
}
|
||||
|
||||
const dog = new Dog("Gino");
|
||||
console.log(dog.name);
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
You can also call methods. In this example, we are calling the `bark()` method on the `dog` instance.
|
||||
|
||||
```js
|
||||
dog.bark();
|
||||
```
|
||||
|
||||
This will log the following message to the console:
|
||||
Here is the full example with the method call included:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
Gino says woof!
|
||||
class Dog {
|
||||
constructor(name) {
|
||||
this.name = name;
|
||||
}
|
||||
bark() {
|
||||
console.log(`${this.name} says woof!`);
|
||||
}
|
||||
}
|
||||
|
||||
const dog = new Dog("Gino");
|
||||
console.log(dog.name);
|
||||
dog.bark();
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
As mentioned earlier, you can also define classes as a class expression. This is where the class is anonymous and assigned to a variable.
|
||||
|
||||
Here is what the earlier example looks like as a class expression:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user