[removed] Two separate scripts - share variables?

前端 未结 5 1215
面向向阳花
面向向阳花 2020-12-08 10:21

If I have two separate scripts in an HTML page with JavaScript are the variables shared between the entire page? Or only within their own declarations?

Example:

5条回答
  •  鱼传尺愫
    2020-12-08 11:10

    In this case, title would be a global variable. You need to encapsulate the variable within a scope. There are various methods for doing so. My preference is a self-executing anonymous function, which would be done like so:

        (function() {
           var title = "Hello world!";
    
           alert(title); // would pop up "Hello World!" since title is in scope
        });
    
        alert(title); // title doesn't exist, because it's outside the scope
    

提交回复
热议问题