Returning a private variable in JavaScript
Posted
by
enrmarc
on Stack Overflow
See other posts from Stack Overflow
or by enrmarc
Published on 2012-10-20T22:39:43Z
Indexed on
2012/10/20
23:00 UTC
Read the original article
Hit count: 182
JavaScript
|variable-scope
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);
© Stack Overflow or respective owner