Can anyone tell the difference between the following two code samples? From the result aspects, they are pretty much the same, but what are the use cases for these two code snippets? Any difference under the hood? Any pitfalls we need to avoid or need to know before we create our object in JavaScript?
var celebrity = {
celebrityID: 999,
getID: function () {
return this.celebrityID;
},
setID: function (theNewID) {
this.celebrityID = theNewID;
}
}
celebrity.getId(); // 999
celebrity.setId(123);
celebrity.getId(); // 123
Vs.
function celebrity () {
var celebrityID = 999;
return {
getID: function () {
return celebrityID;
},
setID: function (theNewID) {
celebrityID = theNewID;
}
}
}
var obj = celebrity();
obj.getID(); // 999
obj.setID(123);
obj.getID(); // 123