繁体   English   中英

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

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

有没有办法在JavaScript中创建私有全局变量? 我试过四处寻找,并且不断谈论构造函数 - 这似乎并不太全局。

谢谢

不确定你的用例是什么。 我假设您有一个包含一些函数和变量的js脚本文件,并且您希望在全局中公开其中一些,但将其余部分保留为脚本文件。 你可以通过关闭实现这一目标。 基本上,您创建一个立即执行的函数。 在函数内部放置原始代码。 然后,将所需的功能导出到全局范围。

// 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

要回答你的问题,不,这是不可能的,因为javascript中没有访问修饰符。 任何函数都可以访问在全局范围内声明的变量。

正如本答案的评论中所指出的,您可以创建具有私有成员的对象。 Crockford 在Javascript中有一个关于私人成员的页面。 他使用以下代码来说明他的观点:

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

在上面的示例中,param,secret和all都是私有的,因为它们无法从外部访问。 更清楚的是,这些变量只能通过特权或私有方法访问,不同之处在于可以从对象的任何实例调用特权方法。 正如评论中所建议的那样,这可以通过使用闭包来实现。

引用Crockford快速解释关闭,但你可以找到很多相关的问题

这意味着内部函数总是可以访问其外部函数的变量和参数,即使在返回外部函数之后也是如此。

为了拥有私人会员。 你需要使用闭包。

以下代码可帮助您理解概念。

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