1

With the code below, customer.name is undefined. Can someone help me understand why and what is going on with the code?

    var customer = function () {
     var name = "Contoso";
     return {
          getName: function () {
                return name;
          },
          setName: function (newName) {
                name = newName;
          }
     };
}();
alert (customer.name);
cmf
  • 435
  • 1
  • 9
  • 21

3 Answers3

1

This is almost a classic JS module pattern - an immediately-invoked function expression (IIFE) that returns an object but which also allows for variable privacy.

I said almost because a module pattern generally looks like this.

var customer = (function () {
  //
})();

The following line scopes a string as a local variable and applies it to name. It cannot be accessed outside of the IIFE because of its scope.

var name = "Contoso";

Because the function is immediately invoked it returns this object an applies it to customer. One method returns the value of name, the other updates it.

return {
  getName: function () { return name; },
  setName: function (newName) { name = newName; }
};

But, because name is "private" to the IIFE (module), customer.name returns undefined.

To get the name use the method on the returned object customer.getName().

To set a new name use the other method customer.setName('Bob').

DEMO

Both these methods have access to the private variable name due to a very important concept know as function closure whereby a function can hang on to ("closes around") its outer lexical environment - useful in this situation, and things like event listeners.

Community
  • 1
  • 1
Andy
  • 61,948
  • 13
  • 68
  • 95
0

When customer.name is called, javascript finds that customer is evaluated to this:

function () {
 var name = "Contoso";
 return {
      getName: function () {
            return name;
      },
      setName: function (newName) {
            name = newName;
      }
 };

The variable name within this function, belongs to the function's memory, or local scope, and is not available anywhere outside of the function. name was declared as var name not as this.name, so it isn't made avaliable through the function, only to the function.

So inside the function, we can say name = blah, but outisde the function we can not. We have to call a function within the function to access it. That's what we have getName and setName for. They are within the function which represents customer and therefore have access to the local variable name.

We could either declare name with this.name within the function, or just change the way we are trying to access customer.name like so:

alert( customer.getName() );
Matt C
  • 4,470
  • 5
  • 26
  • 44
0

The variable customer is undefined, as it outside the scope of the function, at line alert(customer.name);