I have begun writing my ‘class’ type JavaScript functions like the Module Pattern or Revealing Module patten. This avoids the use of ‘new’ and allows me to define which functions are public in a single place. However, I have been unable to see how to use and access public data members in this pattern.
e.g. the member ‘id’ below is accessible through myobj.getId(), but myobj.id is undefined.
function setup(){
var myobj = MyObject();
myobj.initialize();
alert(myobj.getId()); // returns 3, as expected
alert(myobj.id); // returns undefined
}
function MyObject(){
var id;
function initialize(){
//do some stuff that initializes data including...
id = 3;
}
return{
initialize:initialize,
id:id,
getId:function(){ return id;}
}
}
Is there no way to get myobj.id to work returning the value that was set in initialize()?
The reason is that your variable
idis set toundefinedby default and it’s type will beundefinedas well. Now, because undefined type is a primitive one your assignment in the returned object will be a value assignment, not reference. Soobj.idwill becomeundefinedin the instance and not the same as theidvariable in the constructor function.Now
initializewill change theidin the constructor function, andgetIdwill return the sameid, butobj.idwill refer to theundefinedobject property.Run the whole stuff to see it works as expected.