mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-07 06:02:06 -04:00
fix(curriculum): add context for method chaining and this keyword (#66937)
This commit is contained in:
@@ -61,6 +61,38 @@ While method chaining can make code more concise and readable, it's important to
|
||||
|
||||
Very long chains can become difficult to debug, as it's not immediately clear which step in the chain might be causing an issue. It's often a good practice to break very long chains into multiple steps for better clarity and easier debugging.
|
||||
|
||||
You can also chain methods on an object. In this case, each method returns `this`, which refers to the current object, allowing the next method in the chain to run on it.
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
const calculator = {
|
||||
total: 0,
|
||||
add(n) {
|
||||
this.total += n;
|
||||
return this;
|
||||
},
|
||||
multiply(n) {
|
||||
this.total *= n;
|
||||
return this;
|
||||
},
|
||||
subtract(n) {
|
||||
this.total -= n;
|
||||
return this;
|
||||
},
|
||||
getResult() {
|
||||
return this.total;
|
||||
}
|
||||
};
|
||||
|
||||
const result = calculator.add(5).multiply(2).subtract(3).getResult();
|
||||
console.log(result); // 7
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
This way, each method returns the same object, so you can keep chaining calls one after another.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
Reference in New Issue
Block a user