I don’t know why console.log(Set.current_index) shows 0 instead of 3.
var Set = (function() {
var set = [];
var index = 0;
function contains(set, e) {
for (var i = 0; i < set.length; i++) {
if (set[i] === e) {
return true;
}
}
return false;
}
var add = function(e) {
if (!contains(set, e)) {
set[index++] = e;
}
}
var show = function() {
for (var i = 0; i < set.length; i++) {
console.log(set[i]);
}
}
return {
add: add,
show: show,
current_index: index
};
})();
Set.add(20);
Set.add(30);
Set.add(40);
Set.show();
console.log(Set.current_index);
As written
current_indexjust gets the initial value ofindex– it doesn’t mirror any changes to that value because that variable is of primitive type.If you have a ‘reference type’ (i.e. an object or array) then changes to its contents become visible in any other variable that references the same object. That doesn’t happen with primitive types, they’re copied “by value” into the new variables, and changes to the original variable don’t affect the copy.
You need to make
current_indexinto a function that returns the current value ofindex, or write it as agetterwhich allows you to treat.indexas a read-only property by invisibly calling a function to return the current value.For an example of the latter method (which requires ES5, or shims to replicate the functionality) see http://jsfiddle.net/alnitak/WAwUg/, which replaces your current
returnblock with this: