简体   繁体   中英

Use JavaScript global variable which is in a function outside function. Keeping in mind that function is assigned to a variable

How to use the global variable topic outside the function which is assigned to global variable tell.

<html>
<head>
<script>
alert(topic);
tell = function(){
topic = "something";
};
</script>
</head>
<body>
</body>
</html>

Eventually I want to use the value of topic_splitted anywhere outside the function.

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);
    };

It looks like you are not actually running the function "tell". Try this:

<html>
  <head>
    <script>
      var topic;
      var tell = function(){
        topic = "something";
      };
      tell()
      alert(topic);
    </script>
   </head>
  <body>
  </body>
</html>

It is not a good idea to use undeclared variables, such as topic in the tell function of the first post example.

If you assign a value to an undeclared variable, JavaScript creates a global variable for you unless the code is running in strict mode. In strict mode it takes the safer approach of throwing an error that the variable has not been defined.

Where to declare common variables?

If the variable needs to be accessed by code executed at global level when the page loads, it needs to be declared at global level. This is not regarded as desirable and should be avoided if possible.

The alternative is to declare the variable inside a function which might be immediately invoked (an IIFE) or is executed in response to window load or document ready events.. Variables declared within such functions can be accessed by code within the outer function and all functions nested within it.

So if topic_splitted is defined outside all the functions which use it, preferable within a common outer function, there should be no problem.

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