简体   繁体   中英

Way to make global private variables in javascript?

Is there a way to create private global variables in JavaScript? I have tried looking around, and I keep bumping into talk of constructors - which don't seem too global.

Thanks

Not sure what your use case is. I'll assume you have a js script file containing some functions and variables and you want to expose some of those globally, but keep the rest private to your script file. You can achieve this with a closure. Basically you create a function that you execute immediately. Inside the function you place your original code. You then export the functions you need into the global scope.

// Define a function, evaluate it inside of parenthesis
// and execute immediately.
(function(export) {

   var myPrivateVariable = 10;

   function myPrivateFunction(param) {
     return param + myPrivateVariable;
   }

   export.myGlobalFunction = function(someNumber) {
      return myPrivateFunction(someNumber);
   };
})(this);  // The *this* keyword points to *window* which
           // is *the* global scope (global object) in a web browser
           // Here it is a parameter - the *export* variable inside the function.

// This is executed in the global scope
myGlobalFunction(2);  // yields 12 (i.e. 2 + 10)
myPrivateVariable;    // Error, doesn't exist in the global scope
myPrivateFunction(2)  // Error, doesn't exist in the global scope

To answer your question, no, that is not possible as there are no access modifiers in javascript. A variable declared in global scope is accessible to any function.

As pointed out in the comments to this answer, you can create objects which have private members. Crockford has a page on private members in Javascript . He uses the following code to illustrate his point:

function Container(param) {

    // private method
    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;

    // privileged method
    this.service = function () {
        return dec() ? that.member : null;
    };
}

In the above example, param, secret, and that are all private in that they are not accessible from the outside. To be more clear, these variables can only be accessed by privileged or private methods, the difference being that privileged methods can be called from any instance of the object. As is suggested in the comments, this is achievable by using closures.

Quoting from Crockford for a quick explanation on closures, but you can find plenty of related questions .

What this means is that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.

in order to have private members. you need to use closures.

following code help you understanding the concept.

function CustomArray () {
    this.array = [];

    var privateData = 'default data';
    this.getPrivateData = function () {
        return privateData;
    };
    this.setPrivateData = function (data) {
        privateData = data;
    }; 
};

CustomArray.prototype.push = function (data) {
    this.array.push(data);
};

CustomArray.prototype.unshift = function (data) {
    this.array.unshift(data);
};

CustomArray.prototype.pop = function () {
    this.array.pop();
};

CustomArray.prototype.shift = function () {
    this.array.shift();
};

CustomArray.prototype.print = function () {
    console.log(this.array.join(','));
};

var array = new CustomArray();

array.push(10);
array.push(20);
array.push(30);
array.push(5);

array.unshift(3);
array.unshift(2);
array.unshift(1);
array.unshift(0);

array.pop();
array.shift();

array.print();
console.log(array.getPrivateData());// default data 
array.setPrivateData('am new private data');
console.log(array.getPrivateData());//am new private data

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