Uğurcan Erkal
Uğurcan Erkal

Reputation: 53

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

Upvotes: 0

Views: 176

Answers (2)

Rach Chen
Rach Chen

Reputation: 1382

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;
      }
    }
  }
})();

Upvotes: 2

Lorenzo Catalano
Lorenzo Catalano

Reputation: 477

use

return {
    getBalance:getBalance,
    setBalance:setBalance
}

at the end of the function

Upvotes: 4

Related Questions