简体   繁体   中英

Returning a private variable in JavaScript

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_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' (ie 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;

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM