简体   繁体   English

在JavaScript中返回私有变量

[英]Returning a private variable in JavaScript

I don't know why console.log(Set.current_index) shows 0 instead of 3 . 我不知道为什么console.log(Set.current_index)显示0而不是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. 当写入current_index只是获取index初始值-它不会反映对该值的任何更改,因为该变量是原始类型。

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. 您需要使current_index成为一个函数 ,该函数返回index的当前值,或将其写为getter ,以使您可以通过不可见地调用函数以返回.index方式将.index视为只读属性。

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: 有关后一种方法(需要ES5或垫片来复制功能)的示例,请参见http://jsfiddle.net/alnitak/WAwUg/ ,该方法将当前的return块替换为:

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. Javascript总是按值传递,除非变量引用对象。 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 . 因此,您对current_index的初始化只是获取index的初始值,而不是永久指向该变量,因此,在初始化之后,这两个变量使用各自的方式,因此递增index不会递增current_index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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