【发布时间】:2017-01-10 22:16:14
【问题描述】:
如何在分配给全局变量tell的函数之外使用全局变量topic。
<html>
<head>
<script>
alert(topic);
tell = function(){
topic = "something";
};
</script>
</head>
<body>
</body>
</html>
最终我想在函数之外的任何地方使用 topic_splitted 的值。
client.onMessageArrived = function (message) {
topic_splitted = message.destinationName.split("/");
console.log("Topic Splitted: " + topic_splitted);
console.log("Message Topic: " + message.destinationName);
console.log("Message Arrived: " + message.payloadString);
if (message.destinationName == "in_progress"){
if (message.payloadString == "false") {
stepCode();
}
}
var new_data = JSON.parse(message.payloadString);
$.extend(true, data, data, new_data);
};
【问题讨论】:
-
主题必须在警报之前定义,并通过
var topic;运行,然后才能使用 -
您需要在某处调用
tell()来分配变量 -
在函数外定义
topic_splitted,在使用它的函数范围内。 -
@Traktor53 我没明白你的意思抱歉。你能解释一下这将是一个很大的帮助。非常感谢
-
关于您使用
onMessageArrived监听器进行的编辑,您根本不应该使用全局变量。 Use callbacks instead 传递结果。
标签: javascript html scope global-variables