Search code examples
javascriptiife

Uncaught TypeError when try to use IIFE


I'm new at JavaScript and I'm trying to understand to logic of the functions. Here's what I try to do:

var GetterSetter = (function () {
    var balance = 0.0;


    var getBalance = function () {
        return balance;
    };
    var setBalance = function (amount) {
        if (amount > 0) {
           return balance = amount;
        }
      };
})();

GetterSetter.setBalance(120);

When I try to run that. I got :

Uncaught TypeError: Cannot read property 'setBalance' of undefined at GetterSetterScript.js:16


Solution

  • Your GetterSetter does not exist as a method of setBalance.

    You need to set the function in your code. I have provided and example for you:

    code

    var GetterSetter = (function () {
      var balance = 0.0;
      return {
        getBalance: function () {
          return balance;
        },
        setBalance: function (amount) {
          if (amount > 0) {
            return balance = amount;
          }
        }
      }
    })();