[英]Do I need to specify object type when creating globals in Javascript?
我有以下代碼:
var oTable = $('#dataTable').dataTable({
...
我想將oTable聲明為全局表,但我有些困惑。 使用javascript如何做到這一點,並且在將其聲明為全局對象時是否必須指定對象類型?
簡單地說,你沒有。 您只需像聲明變量一樣聲明該變量,然后在需要時使用它。
當您要在函數中使用全局變量時,只需鍵入其名稱即可,而無需先聲明它。
例
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'
}
您可以像這樣全局地聲明它。 Var是通用類型,可以將任何類型分配給它。
var oTable = $('#dataTable').dataTable({......
function someFunction()
{
}
全局變量實際上不是變量,而是全局對象的屬性。 可以將它們明確附加如下:
window.oTable = $('#dataTable').dataTable({});
window
是指瀏覽器javascript中的全局對象。
您不能聲明類型。
除非使用var
在函數內定義變量,否則它將是全局變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.