آموزش مقدماتی جاوا اسکریپت| CLOSURES | قسمت 52

تعداد بازدید : 5 | تاریخ انتشار : 16 اردیبهشت 1403 15:19 | مدت زمان : 00:10:57 | دسته بندی : فناوری و رایانه

در این دوره آموزشی قصد داریم تا شما را با اصول برنامه نویسی با زبان قدرتمندJavaScript اشنا کنیم. این مجموعه آموزشی یک مجموعه کامل برای آموزش زبان برنامه نویسی JavaScript است . // closure = A function defined inside of another function, // the inner function has access to the variables // and scope of the outer function. // Allow for private variables and state maintenance // Used frequently in JS frameworks: React, Vue, Angular 00:00:00 intro 00:00:31 example 1 00:02:19 example 2 00:07:00 example 3 00:10:08 conclusion // --------- EXAMPLE 1 --------- function outer(){ const message = "Hello"; function inner(){ console.log(message); } inner(); } message = "Goodbye"; outer(); // --------- EXAMPLE 2 --------- function createCounter() { let count = 0; function increment() { count++; console.log(`Count increased to ${count}`); } function getCount() { return count; } return {increment, getCount}; } const counter = createCounter(); counter.increment(); counter.increment(); counter.increment(); console.log(`Current count: ${counter.getCount()}`); // --------- EXAMPLE 3 --------- function createGame(){ let score = 0; function increaseScore(points){ score += points; console.log(`+${points}pts`); } function decreaseScore(points){ score -= points; console.log(`-${points}pts`); } function getScore(){ return score; } return {increaseScore, decreaseScore, getScore}; } const game = createGame(); game.increaseScore(5); game.increaseScore(6); game.decreaseScore(3); console.log(`The final score is ${game.getScore()}pts`);