Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

IIFE module pattern in javascript

const makeWithdraw = balance => (function(copyBalance) {
  let balance = copyBalance; // This variable is private
  let doBadThings = function() {
    console.log("I will do bad things with your money");
  };
  doBadThings();
  return {
    withdraw: function(amount) {
      if (balance >= amount) {
        balance -= amount;
        return balance;
      } else {
        return "Insufficient money";
      }
    },
  }
})(balance);

const firstAccount = makeWithdraw(100); // "I will do bad things with your money"
console.log(firstAccount.balance); // undefined
console.log(firstAccount.withdraw(20)); // 80
console.log(firstAccount.withdraw(30)); // 50
console.log(firstAccount.doBadThings); // undefined; this method is private
const secondAccount = makeWithdraw(20); // "I will do bad things with your money"
console.log(secondAccount.withdraw(30)); // "Insufficient money"
console.log(secondAccount.withdraw(20));  // 0
Comment

PREVIOUS NEXT
Code Example
Javascript :: template.json input parameters 
Javascript :: spread operator shorthand javascript 
Javascript :: get selected value of select2 dropdown in jquery 
Javascript :: NestJs starter repo 
Javascript :: react js practical tutorial 
Javascript :: close element on click outside 
Javascript :: where in typeorm 
Javascript :: using fetch hook 
Javascript :: errorhandler npm 
Javascript :: JS call url many times 
Javascript :: string format javascript 
Javascript :: how to add multiple quill rich text editor 
Javascript :: arrow function with computed property vue 
Javascript :: Previously visited page with vanilla JavaScript 
Javascript :: jquery ui music player 
Javascript :: wakatime cli installation via npm 
Javascript :: int[] arr = new int[5]; for(int i=0; i<arr.length; i++){ arr[i] = i; } for(int i=0; i<arr.length; i++) { System.out.print(arr[i]); } 
Javascript :: playwrigth await browser 
Javascript :: change class on resize window jquery 
Javascript :: typeorm class validator 
Javascript :: hex decode javascript 
Javascript :: serverless web app with react netlify 
Javascript :: Using the Unshift() Method to Reverse an Array 
Javascript :: const and let keywords in ES6 
Javascript :: react clearinterval outside of useefect 
Javascript :: merge json data in main.go in golang 
Javascript :: External javascript in React Native 
Javascript :: How do you convert VARCHAR to TIMESTAMP 
Javascript :: python to javascript converter 
Javascript :: event module 
ADD CONTENT
Topic
Content
Source link
Name
7+4 =