work
This commit is contained in:
parent
1bffa43db4
commit
057783d216
373 changed files with 203 additions and 190 deletions
|
@ -0,0 +1,40 @@
|
|||
The solution is to return the object itself from every call.
|
||||
|
||||
```js run
|
||||
let ladder = {
|
||||
step: 0,
|
||||
up() {
|
||||
this.step++;
|
||||
*!*
|
||||
return this;
|
||||
*/!*
|
||||
},
|
||||
down() {
|
||||
this.step--;
|
||||
*!*
|
||||
return this;
|
||||
*/!*
|
||||
},
|
||||
showStep() {
|
||||
alert( this.step );
|
||||
*!*
|
||||
return this;
|
||||
*/!*
|
||||
}
|
||||
}
|
||||
|
||||
ladder.up().up().down().up().down().showStep(); // 1
|
||||
```
|
||||
|
||||
We also can write a single call per line. For long chains it's more readable:
|
||||
|
||||
```js
|
||||
ladder
|
||||
.up()
|
||||
.up()
|
||||
.down()
|
||||
.up()
|
||||
.down()
|
||||
.showStep(); // 1
|
||||
```
|
||||
|
39
1-js/3-object-basics/3-object-methods/8-chain-calls/task.md
Normal file
39
1-js/3-object-basics/3-object-methods/8-chain-calls/task.md
Normal file
|
@ -0,0 +1,39 @@
|
|||
importance: 2
|
||||
|
||||
---
|
||||
|
||||
# Chaining
|
||||
|
||||
There's a `ladder` object that allows to go up and down:
|
||||
|
||||
```js
|
||||
let ladder = {
|
||||
step: 0,
|
||||
up() {
|
||||
this.step++;
|
||||
},
|
||||
down() {
|
||||
this.step--;
|
||||
},
|
||||
showStep: function() { // shows the current step
|
||||
alert( this.step );
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
Now, if we need to make several calls in sequence, can do it like this:
|
||||
|
||||
```js
|
||||
ladder.up();
|
||||
ladder.up();
|
||||
ladder.down();
|
||||
ladder.showStep(); // 1
|
||||
```
|
||||
|
||||
Modify the code of `up` and `down` to make the calls chainable, like this:
|
||||
|
||||
```js
|
||||
ladder.up().up().down().showStep(); // 1
|
||||
```
|
||||
|
||||
Such approach is widely used across Javascript libraries.
|
Loading…
Add table
Add a link
Reference in a new issue