I am trying to check if I can build JavaScript objects as intuitively as possible, making sure that it is “correct” as much as possible. I ran a bunch of different scripts through Crockford JSLint.com and didn't have much luck. It seems I fixed one error, then another pops up due to a change. The following is about as good as I can get. Anyone else take on this?
This is a typical way to structure an object:
function gizmo(id) {
var myId = id;
var init = function () {
if (myId < 1) {
setId(1);
}
};
var setId = function (newId) {
myId = newId;
};
init();
return {
getId: function () {
return myId;
},
setId: function (newId) {
setId(newId);
},
incrementId: function (inc) {
setId(myId + inc);
}
};
}
var myGizmo = gizmo(-2);
console.log(myGizmo.getId());
myGizmo.setId(5);
console.log(myGizmo.getId());
myGizmo.incrementId(2);
console.log(myGizmo.getId());
This seems to work well. However, when I run it through JSLint, it gives me an error stating that my two private functions are "Implied Global".
The best I can come up with is to declare my functions on top with the following variables:
function gizmo(id) {
var myId = id,
init,
setId;
init = function () {
if (myId < 1) {
setId(1);
}
};
setId = function (newId) {
myId = newId;
};
init();
return {
getId: function () {
return myId;
},
setId: function (newId) {
setId(newId);
},
incrementId: function (inc) {
setId(myId + inc);
}
};
}