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