[英]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.