简体   繁体   中英

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. With javascript how do I do this and do I have to specify the object type when I declare it as a global?

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

Unless that declaration is inside of a function, oTable is already a global variable. Also, Javascript is dynamically-typed, which means you're not can't define the variable type.

For more information on global variables in Javascript, check out this article.
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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