简体   繁体   English

在javascript中创建全局私有变量的方法?

[英]Way to make global private variables in javascript?

Is there a way to create private global variables in JavaScript? 有没有办法在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. 我假设您有一个包含一些函数和变量的js脚本文件,并且您希望在全局中公开其中一些,但将其余部分保留为脚本文件。 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. 要回答你的问题,不,这是不可能的,因为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 . Crockford 在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. 在上面的示例中,param,secret和all都是私有的,因为它们无法从外部访问。 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 . 引用Crockford快速解释关闭,但你可以找到很多相关的问题

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

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

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