无法访问被声明为全局变量并在click函数中初始化的变量



我试图访问被声明为全局变量并在onclick函数内初始化的变量。

onclick函数之外不可访问。

在代码"ClickedChillerName";是我在onclicked函数中声明为全局并初始化的变量。
点击后,我正在重新加载页面。

虽然我想访问"ClickedChillerName";在外面它给出了undefined

window.onload = function() {
initAuth('Line chart and events table using the PAYG SKU');  // initiate auth objects, header, and login modal
var tsiClient = new TsiClient();
//var ChillerName;
var linechartTsqExpressions = [];
var startDate = new Date('2021-01-27T04:20:00Z');
console.log('date : '+startDate);
var endDate = new Date(startDate.valueOf() + 1000*60*60*4);
//var ClickedChillerName;
console.log("step4"+ClickedChillerName);
linechartTsqExpressions.push(new tsiClient.ux.TsqExpression({timeSeriesId: [ClickedChillerName]}, // instance json
{Max: {
kind: 'numeric',
value: {tsx: '$event.temperature.Double'},
filter: null,
aggregation: {tsx: 'max($value)'}
}}, // variable json
{ from: startDate, to: endDate, bucketSize: '1m' }, 
'#60B9AE', // color
'MaxValue')); // alias
// onInstanceClick Function start
var onInstanceClick = function(instance) { 
$(".tsi-name").click(function() {
console.log(this.innerHTML);
window.location.reload();
ClickedChillerName=this.innerHTML;
console.log(ClickedChillerName+"Name");
console.log("Step1");
});
console.log(ClickedChillerName+"Name2");
console.log("Step2");
let contextMenuActions = [];
authContext.getTsiToken()
.then(token => { 
tsiClient.server.getTimeseriesTypes(token, 'Test.env.timeseries.azure.com', [instance.type.id])
.then(r => {
if (r.get && Array.isArray(r.get)) {
r.get.forEach((t) => {
let type = t.timeSeriesType;
Object.keys(type.variables).forEach((vName) => {
let option = {};
if (type.variables[vName].aggregation.tsx === 'avg($value)') {
let newType = this.getTsmTypeFromVariable(type.variables[vName]);
option['name'] = vName;
option['action'] = () => addInstanceAction(newType, vName, instance);
} else {
option['name'] = vName;
option['action'] = () => addInstanceAction(instance.type, vName, instance);
}
contextMenuActions.push(option);
});
});
hierarchy.drawContextMenu(contextMenuActions, {});
}
})
});
}
}

理解JavaScript作用域

在JavaScript中有两种作用域:

本地范围全球范围

JavaScript有函数作用域:每个函数创建一个新的作用域。

函数内部定义的变量不能从函数外部访问(可见)。

本地JavaScript变量在JavaScript函数中声明的变量,对函数来说是LOCAL的。

局部变量具有函数作用域:它们只能在函数内部被访问。

// code here can NOT use carName
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}

so your//var ClickedChillerName;对于函数来说是局部的,这就是为什么你可以从外部访问它——"未定义的";你得到的价值。

JavaScript全局变量在函数外部声明的变量变为GLOBAL。

全局变量具有全局作用域:web页面上的所有脚本和函数都可以访问它。

var carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}

更多信息在这里:https://www.w3schools.com/js/js_scope.asp

最新更新