1

the following factory function has on = false.

function Radio(mode) {
  let on = false;

  return {
    mode: mode,
    turnOn: function () {
      on = true;
    },
    isOn: function () {
      return on;
    }
  };
}

If I created an object using this factory function and used the function fmRadio.turnOn(); inside it to change the value of on to be true like in the following lines..

let fmRadio = Radio('fm');

fmRadio.turnOn();

The output of fmRadio.isOn(); will be on = true

So, Where does on variable change? I mean it's not part of the fmRadio object created..if we tried to call it it will return undefined

fmRadio.on;
//undefined

Does it change the value of on in the original factory function?

Andrew Jons
  • 125
  • 1
  • 7

1 Answers1

1

Variable on exists only on the scope of the function. When you are trying to access the on variable, that on variable is not exposed for usage outside the function as the function is returning only the object with mode, turnOn and turnOff. You can think of this variable (on) as its a private declard variable and it doesn't have any access from outside of the class (of course it's not like that since here you have a function, but to give you an example). If you return the on variable from the function, you will have access on that variable using ObjectName.on

what you can do is

function Radio(mode) {
  let on = "test";

  return {
    getOn: function() { 
        return on;
    },
    setOn: function(value) { 
        on = value;
    },
    mode: mode,
    turnOn: function () {
      on = true;
    },
    isOn: function () {
      return on;
    }
  };
}

in this case I think you can understand it better, I created two other functions, one of the functions to get the value of variable on the other one to set the value, same like getters and setters in java or c#.

now if you get the value of variable on via function getOn, the value "test" will be returned, but if you set it to another value via setOn function the variable on will be set to the new value and next time you get the updated value. This helps if you want to keep variables read only e.g

Rinor Dreshaj
  • 1,032
  • 12
  • 24
  • as far as I understood, `on` is like a part of the object created but it can't be accessed by this object until the inner function is invoked. is that right? – Andrew Jons Jun 26 '20 at 13:59
  • I've updated the answer once again to make it more clear, yes it is a part of the object because the function contains a declaration, but is not returned from that function (meaning is not exposed for usage outside of that function) – Rinor Dreshaj Jun 26 '20 at 14:05