Javascript 命名空间中的全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13012238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Global variable in Javascript Namespace
提问by Anirban Ghosh
I m new with Javascript Namespace, I have 2 buttons Add
& Remove
, I have the following script below.
我是 Javascript 命名空间的新手,我有 2 个按钮Add
& Remove
,下面有以下脚本。
<script>
var nRow=1;
function Add() {
nRow++;
alert(nRow);
}
function Remove() {
nRow--;
alert(nRow);
}
</script>
What I'm trying to do to put this script in a namespace and call the functions onClick
of the buttons. Please tell me how to put it in namespace and call the functions.
我试图将这个脚本放在一个命名空间中并调用onClick
按钮的功能。请告诉我如何将其放入命名空间并调用函数。
回答by BenM
Technically, JavaScript doesn't support namespaces. You could place it inside an object as follows:
从技术上讲,JavaScript 不支持命名空间。你可以把它放在一个对象中,如下所示:
var Increment = {
nRow : 1,
Add : function() {
this.nRow++;
alert(this.nRow);
},
Remove : function() {
this.nRow--;
alert(this.nRow);
}
}
You can then access the functions via Increment.Add()
and Increment.Remove()
.
然后,您可以通过Increment.Add()
和访问这些功能Increment.Remove()
。
回答by SReject
Javascript doesn't have namespaces or classes. It has objects and prototypes. With that said, this should be what I believe you are asking for:
Javascript 没有命名空间或类。它有对象和原型。话虽如此,这应该是我相信您要求的:
<script>
window.myNameSpace = {
nRow: 1,
add: function () {
this.nRow++;
alert(this.nRow);
},
remove: function() {
this.nRow++;
alert(this.nRow);
}
};
document.getElementById("MyAddButtonId").addEventListener("click", myNameSpace.add, false);
document.getElementById("MyRemoveButtonId").addEventListener("click", myNameSpace.remove, false);
</script>