-
[JS] chapter14. ๊ฐ์ฒด ์งํฅ - ํด๋ก์ ๋ชจ๋ ํจํดcodeStates front-end/Java Script 2023. 1. 13. 10:40๋ฐ์ํ
๐ํด๋ก์ ๋ชจ๋ ํจํด
๋ฉ์๋ ํธ์ถ
๊ฐ์ฒด.๋ฉ์๋() -> ๊ฐ์ฒด ๋ด์ ๋ฉ์๋๋ฅผ ํธ์ถํ๋ ๋ฐฉ๋ฒ
โ ๏ธ ํ์ดํ ํจ์ x
์นด์ดํฐ ๊ตฌํ ์์
let counter1 = { value: 0, increase: function() { this.value++ // ๋ฉ์๋ ํธ์ถ์ ํ ๊ฒฝ์ฐ, this๋ counter1์ ๊ฐ๋ฆฌํต๋๋ค }, decrease: function() { this.value-- }, getValue: function() { return this.value } } counter1.increase() counter1.increase() counter1.increase() counter1.decrease() counter1.getValue() // 2
ํด๋ก์ ๋ฅผ ์ด์ฉํด ๋งค๋ฒ ์๋ก์ด ๊ฐ์ฒด ์์ฑ
ํด๋ก์ ๋? ํจ์๋ฅผ ๋ฆฌํดํ๋ ํจ์
https://hwantech.tistory.com/146
[JS] Chapter 8. ํด๋ก์
ํด๋ก์ ํจ์๋ฅผ ๋ฆฌํดํ๋ ํจ์ // ํด๋ก์ ํจ์์ ๊ธฐ๋ณธ ํํ const adder = function (x) { return function(y) { // ๋ฆฌํด๊ฐ์ด ํจ์์ ํํ return x+y; } } ์ธ๋ถ ํจ์์ ๋ด๋ถ ํจ์ ๋ฆฌํดํ๋ ํจ์์ ์ํด ์ค์ฝํ(๋ณ์์
hwantech.tistory.com
์์ ์ฝ๋์์ counter1์ ๋จ ํ๋์ ๊ฐ์ฒด๋ง ๋ง๋ค ์ ์๋ค.
์นด์ดํฐ๋ฅผ ์ฌ๋ฌ ๊ฐ๋ฅผ ๋ง๋ค๊ณ ์ถ๋ค๋ฉด? -> ํด๋ก์ ๋ชจ๋ ํจํด ์ฌ์ฉ
์นด์ดํฐ ๊ตฌํ ์์ (ํด๋ก์ ๋ชจ๋ ํจํด)
function makeCounter() { let value = 0; return { increase: function() { value++; }, decrease: function() { value--; }, getValue: function() { return value; } } } let counter1 = makeCounter() counter1.increase() counter1.getValue() // 1 let counter2 = makeCounter() counter2.decrease() counter2.decrease() counter2.getValue() // -2
๋ฐ์ํ'codeStates front-end > Java Script' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JS] chapter16. ๊ฐ์ฒด ์งํฅ - ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋๋ฐ (0) 2023.01.13 [JS] chapter15. ๊ฐ์ฒด ์งํฅ - ํด๋์ค์ ์ธ์คํด์ค (0) 2023.01.13 [JS] chapter14. ๋ด์ฅ๊ณ ์ฐจํจ์ (0) 2023.01.12 [JS] chapter13. ๊ณ ์ฐจํจ์ (0) 2023.01.12 [JS] chapter12. ์ด๋ฒคํธ ๊ฐ์ฒด (0) 2023.01.06