[英]Do I need to specify object type when creating globals in Javascript?
I have the following code: 我有以下代码:
var oTable = $('#dataTable').dataTable({
...
I would like to declare oTable as a global but I am a bit confused. 我想将oTable声明为全局表,但我有些困惑。 With javascript how do I do this and do I have to specify the object type when I declare it as a global?
使用javascript如何做到这一点,并且在将其声明为全局对象时是否必须指定对象类型?
Put simply, you don't. 简单地说,你没有。 You just declare the variable as you did, and use it wherever you need.
您只需像声明变量一样声明该变量,然后在需要时使用它。
When you'll want to use a global variable in a function, you can simply type its name, without declaring it first. 当您要在函数中使用全局变量时,只需键入其名称即可,而无需先声明它。
Example 例
var MyVar = $('#dataTable').dataTable(); // This is a global variable. Notice that you don't specify a type, as JavaScript is not strongly typed
function MyFunction() {
var InternalVar = MyVar; // Here you take the value from the global variable, i.e. the datatable
}
function MyOtherFunction() {
var MyVar = 'This is a string';
var InternalVar = MyVar; // Here you take the value from the LOCAL variable, which you declared just above, i.e. 'This is a string'
}
You can declare it globally like this without any problem. 您可以像这样全局地声明它。 Var is generic type and any type could be assigned to it.
Var是通用类型,可以将任何类型分配给它。
var oTable = $('#dataTable').dataTable({......
function someFunction()
{
}
Global variables are not actually variables, but properties of the global object. 全局变量实际上不是变量,而是全局对象的属性。 They can be explicitly attached as follows:
可以将它们明确附加如下:
window.oTable = $('#dataTable').dataTable({});
window
refers to the global object in browser javascript. window
是指浏览器javascript中的全局对象。
Unless that declaration is inside of a function, oTable
is already a global variable. 除非该声明在函数内部,
oTable
已经是全局变量。 Also, Javascript is dynamically-typed, which means you're not can't define the variable type. 另外,JavaScript是动态类型的,这意味着您无法定义变量类型。
For more information on global variables in Javascript, check out this article. JavaScript中的全局变量的更多信息,请查看此文章。
For more information on static vs dynamic typed, check out this question. 有关静态类型和动态类型的更多信息,请查看此问题。
You can't declare a type. 您不能声明类型。
Unless the variable is defined within a function using var
it'll be a global. 除非使用
var
在函数内定义变量,否则它将是全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.