|
| 1 | +function counter () { |
| 2 | + let myCounter = 0; |
| 3 | + const myFunction = function() { |
| 4 | + return myCounter++; |
| 5 | + } |
| 6 | + return myFunction; |
| 7 | +} |
| 8 | + |
| 9 | +const newCounter = counter(); |
| 10 | + |
| 11 | +console.log(newCounter()); |
| 12 | +console.log(newCounter()); |
| 13 | +console.log(newCounter()); |
| 14 | +console.log(newCounter()); |
| 15 | +console.log(newCounter()); |
| 16 | +console.log(newCounter()); |
| 17 | + |
| 18 | + |
| 19 | +// TASK 1 |
| 20 | + |
| 21 | +function helloWorldClosure(str) { |
| 22 | + let emptyString = ''; |
| 23 | + return function (str) { |
| 24 | + return emptyString += str + ' '; |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +const helloWorld = helloWorldClosure(); |
| 29 | + |
| 30 | +console.log(helloWorld('hello')); |
| 31 | +console.log(helloWorld('world')); |
| 32 | +console.log(helloWorld('privet na 100 let')); |
| 33 | + |
| 34 | +// TASK 2 |
| 35 | + |
| 36 | +function plusSomething(number) { |
| 37 | + return function(closureNumber) { |
| 38 | + return number += closureNumber; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +const numberTwenty = plusSomething(10); |
| 43 | +console.log(numberTwenty(20)); |
| 44 | +console.log(numberTwenty(20)); |
| 45 | +console.log(numberTwenty(20)); |
| 46 | + |
| 47 | +// TASK 3 |
| 48 | + |
| 49 | + |
| 50 | +/* |
| 51 | +* напишите функцию которая будет возвращать объект |
| 52 | +* |
| 53 | +* и у этого объекта будет свойство которое будет равняться |
| 54 | +* функции |
| 55 | +* add() {} |
| 56 | +* при вызове этого свойства отобразите в консоле 1 |
| 57 | +
|
| 58 | +const myCounter = createCounter(); |
| 59 | +myCounter.add() // 1 |
| 60 | +myCounter.add() // 2 |
| 61 | +myCounter.add() // 3 |
| 62 | +*/ |
| 63 | + |
| 64 | +function returnObject(number) { |
| 65 | + let counter = number; |
| 66 | + let saveState = 0; |
| 67 | + let obj = { |
| 68 | + add: function() { |
| 69 | + saveState = counter; |
| 70 | + return ++counter; |
| 71 | + }, |
| 72 | + addTen: function() { |
| 73 | + saveState = counter; |
| 74 | + return counter += 10; |
| 75 | + }, |
| 76 | + lastState: function() { |
| 77 | + return `PREV State ${saveState}`; |
| 78 | + } |
| 79 | + } |
| 80 | + return obj; |
| 81 | +} |
| 82 | + |
| 83 | +const myCounter = returnObject(10); |
| 84 | + |
| 85 | +console.log(myCounter.add()); |
| 86 | +console.log(myCounter.add()); |
| 87 | +console.log(myCounter.add()); |
| 88 | +console.log(myCounter.add()); |
| 89 | +console.log(myCounter.lastState()); |
| 90 | +console.log(myCounter.add()); |
| 91 | +console.log(myCounter.add()); |
| 92 | +console.log(myCounter.addTen()); |
| 93 | +console.log(myCounter.lastState()); |
0 commit comments