I have a JavaScript class like this:
Dog = (function() {
var name;
function setName(_name) {
name = _name;
}
return {
setName: setName,
name: name
};
})();
When I run:
Dog.setName('Hero');
Dog.name
is always undefined.
I am certainly missing something about JS scoping, but what?
You are returning an object where
name
property has a value ofname
at that point in time (which is undefined). Thename
property of the returned object is not somehow dynamically updated when thename
variable inside the IIFE is updated.There are many ways to handle what you appear to be wanting to do. Here's one:
This keeps
name
as a private variable, which can only be set viasetName
, but provides a getter property for obtaining its value.The alternative proposed in another answer is equivalent, just a different way of writing it:
Minor point, but in this particular context you don't need parentheses around your IIFE:
will work fine.
Use the 'this' keyword.
This happens because you assume that setting
name
in the object retains a reference to the originalname
variable. Instead, you want to assign it to the current object (which, you might as well ignore the private variable altogether).However, if you want to keep
name
private then you create a getter for it instead.Sounds like you want to make a constructor... Check this sample:
you can try it here: http://jsfiddle.net/leojavier/ahs16jos/
I hope this helps man...
The easy way to fix this is:
In your code, you were setting the wrong
name
variable.var name;
In this function, setName is setting the internal variable
name
and not the propertyname
. In JavaScript, strings are immutable, so when you change it, it creates a new string, and doesn't update the existing one.This might be a better pattern for you. You're using the very old ES3 style constructor.
You might want to look into ES6 classes too