mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-08-31 01:14:08 +08:00
refactor(curriculum): update section headers for "How Does the This Keyword Work" (#69355)
This commit is contained in:
committed by
GitHub
parent
57faa5eb56
commit
734dd74b59
+10
@@ -11,6 +11,8 @@ You learned that classes are like blueprints that you can use to create objects.
|
||||
|
||||
These blueprints need a general way to refer to the specific object that is being created, accessed, or modified within the code. That's exactly what the `this` keyword is used for. It refers to the context where the code is supposed to run. If you use it within a method, the value of `this` will be a reference to the object associated to that method. This way, you can access the properties and methods of the object within the class and reuse the method on different objects.
|
||||
|
||||
## Constructors
|
||||
|
||||
For example, here we have a `Dessert` class. This time, we're defining a `hasPeanuts` property.
|
||||
|
||||
```js
|
||||
@@ -33,6 +35,8 @@ this.hasPeanuts = hasPeanuts;
|
||||
|
||||
That's in the context of the constructor but you can also use the `this` keyword within other methods.
|
||||
|
||||
## Methods
|
||||
|
||||
This is our `Dessert` class with a few changes. Now we have two properties: `name` and `price`.
|
||||
|
||||
```js
|
||||
@@ -91,10 +95,16 @@ The name and price of the current object (`brownie`) are replaced in the string.
|
||||
|
||||
This is all thanks to the `this` keyword, which gives you a general way to refer to the current object within the class. This allows you to reuse the method on different objects.
|
||||
|
||||
## Functions And Arrow Functions
|
||||
|
||||
This is in the context of object methods but the `this` keyword will also have a value in standalone functions and arrow functions.
|
||||
|
||||
### Regular Functions
|
||||
|
||||
Its value within a standalone function typically refers to the global object (in non-strict mode) or `undefined` (in strict mode).
|
||||
|
||||
### Arrow Functions
|
||||
|
||||
The value of the `this` keyword is a bit different in arrow functions. Arrow functions inherit the value of `this` from the enclosing scope where they are defined. They don't create their own `this` binding. That means that the value of `this` depends on the context where the arrow function is defined, not where or how the arrow function is called. This makes arrow functions helpful for callbacks or for preserving context.
|
||||
|
||||
However, because of this, the value of `this` will not refer to the current object in object methods, so this is something that you should keep in mind when working with arrow functions.
|
||||
|
||||
Reference in New Issue
Block a user