I came across this on Mozilla's tutorials on JavaScripts and I cant seem to understand it. I read a lot of stackoverflow questions but I could not find an answer to my question. Given below is a code snippet.
var createPet = function(name) {
var sex;
return {
setName: function(newName) {
name = newName;
},
getName: function() {
return name;
},
getSex: function() {
return sex;
},
setSex: function(newSex) {
if(typeof newSex == "string" && (newSex.toLowerCase() == "male" || newSex.toLowerCase() == "female")) {
sex = newSex;
}
}
}
}
var pet = createPet("Vivie");
var pet2 = createPet("Sam");
pet.getName(); // Vivie
pet2.getName(); // Sam
createPet
only seems to return a map of function objects but there is no mention of variable name
anywhere but somehow, pet
and pet2
behave like objects of a class with a member variable named name
and a bunch of member functions like getName()
, setName()
etc. How does this work?