1

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);

2 Answers 2

4

As written current_index just gets the initial value of index - 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_index into a function that returns the current value of index, or write it as a getter which allows you to treat .index as 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 return block with this:

var interface = {
    add: add,
    show: show
};

Object.defineProperty(interface, 'index', {
    get: function() {
        return index;
    },
    enumerable: true
});

return interface;
Sign up to request clarification or add additional context in comments.

5 Comments

Or just don't use a private index variable but the public property in the add method
@Bergi I suspect that the private encapsulation is important to the design of this function.
Yes, possible. The OP needs to decide what he wants
Ok, I get it. But I don't understand it doesn't mirror any changes to that value because that variable is of primitive type.
@enrmarc I've added some additional text.
1

Javascript always passes by value except when a variable refers to an object. So your initialization of current_index just gets the initial value of index rather than permanently pointing to the variable, so after that initialization, the two variables are on their separate ways therefore incrementing index doesn't increment current_index.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.