How to turn local variables into global variables in JavaScript

How to turn local variables into global variables in JavaScript

First we need to know the self-calling of the function

Function self-calling - self-calling function

One-time function - declared and called directly, for example:

(function () {
  console.log("function");

})();

We will see that the browser directly prints the two words "函數"

After the page is loaded, the code of this self-calling function is executed.

Use form

(function (parameters) {
  
})(actual parameter);

Notice

When calling a constructor from scratch, a semicolon must be added

So how do you turn a local variable into a global variable?

Just give the local variable to window

(function (win) {
  var num=10;//local variable//js is a dynamically typed language, objects have no attributes, just click on them win.num=num;
})(window);
console.log(num);

The page prints out num

insert image description here

Application Case 1——Assigning a random number object to window

insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>title</title>
  <script>

     //Generate a random number object through a self-calling function. Outside the self-calling function, call the random number object method to generate a random number (function (window) {
       //Constructor function to generate random numbers function Random() {
       }
       //Add method to prototype object Random.prototype.getRandom = function (min,max) {
         return Math.floor(Math.random()*(max-min)+min);
       };
       //Expose the Random object to the top-level object window--->This object can be used directly outside window.Random=Random;
     })(window);
     //Instantiate random number object var rm=new Random();
     //Call method to generate random number console.log(rm.getRandom(0,5));



    //Global variables</script>
</head>
<body>


</body>
</html>

Application Case 2 - Generate small squares at random positions

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta>
  <title>title</title>
  <style>
    .map{
      width: 800px;
      height: 600px;
      background-color: #CCC;
      position: relative;
    }
  </style>
</head>
<body>
<div class="map"></div>
<script src="common.js"></script>
<script>
  //Generate random number object (function (window) {
    function Random() {
    }
    Random.prototype.getRandom=function (min,max) {
      return Math.floor(Math.random()*(max-min)+min);
    };
    //Expose the local object to the window top-level object, and it becomes a global object window.Random=new Random();
  })(window);//Self-calling constructor method, semicolon must be added//Generate a small square object (function (window) {
    //console.log(Random.getRandom(0,5));
    //Use the selector method to get the element object var map = document.querySelector(".map");

    //Food constructor function Food(width,height,color) {
      this.width=width||20;//Default width of the small square this.height=height||20;//Default height of the small square //Horizontal coordinate, vertical coordinate this.x=0;//Horizontal coordinate is randomly generated this.y=0;//Vertical coordinate is randomly generated this.color=color;//Background color of the small square this.element=document.createElement("div");//Element of the small square }
    //Initialize the display effect and position of the small square---display on the map Food.prototype.init=function (map) {
      //Set the style of the small square var div=this.element;
      div.style.position="absolute";//Out of document flow div.style.width=this.width+"px";
      div.style.height=this.height+"px";
      div.style.backgroundColor=this.color;
      //Add the small square to the map map.appendChild(div);
      this.render(map);
    };
    //Generate random positions Food.prototype.render = function (map) {
      //Randomly generate horizontal and vertical coordinates var x=Random.getRandom(0,map.offsetWidth/this.width)*this.width;
      var y=Random.getRandom(0,map.offsetHeight/this.height)*this.height;
      this.x=x;
      this.y=y;
      var div = this.element;
      div.style.left=this.x+"px";
      div.style.top=this.y+"px";
    };

    //Instantiate the object var fd = new Food(20,20,"green");
    fd.init(map);
    console.log(fd.x+"===="+fd.y);

    
  })(window);


  // function refresh(){
  // window.location.reload();
  // }
  // setTimeout(refresh(), 1000);
</script>
</body>
</html>

This is the end of this article about how to turn local variables into global variables in JavaScript. For more information about how to turn local variables into global variables in JavaScript, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • In-depth understanding of JavaScript variable objects
  • JavaScript variables and transformation details
  • Do you understand JavaScript variable types and conversions between variables?
  • Do you know variable declaration in JavaScript?
  • JavaScript Basics Variables
  • A brief talk about JavaScript variable promotion
  • Detailed explanation of JS ES6 variable destructuring assignment
  • Javascript beginner's guide to string concatenation and variable applications
  • A brief analysis of the principles and usage examples of JS variable promotion
  • Use of variables in JavaScript

<<:  How to install MySQL 5.7 on Ubuntu and configure the data storage path

>>:  Solve the problem of Chinese garbled characters when inserting data into MySQL by Tomcat under Linux

Recommend

MySQL date and time addition and subtraction sample code

Table of contents 1.MySQL adds or subtracts a tim...

How to configure nginx to return text or json

Sometimes when requesting certain interfaces, you...

React Diff Principle In-depth Analysis

Table of contents Diffing Algorithm Layer-by-laye...

Two simple ways to remove text watermarks from web pages

<br /> When we browse certain websites and s...

JavaScript implements circular progress bar effect

This article example shares the specific code of ...

Linux hardware configuration command example

Hardware View Commands system # uname -a # View k...

WeChat applet realizes the function of uploading pictures

This article example shares the specific code for...

Solution to MySQL 8.0 cannot start 3534

MySQL 8.0 service cannot be started Recently enco...

Share 20 JavaScript one-line codes

Table of contents 1. Get the value of browser coo...

How to query json in the database in mysql5.6 and below

When saving data in MySQL, sometimes some messy a...

MySQL 5.7.17 compressed package installation-free configuration process diagram

There are two versions of MySQL database manageme...

Solution to the IP address not being displayed under Linux

Table of contents Preface Solution: Step 1 Step 2...

Window.name solves the problem of cross-domain data transmission

<br />Original text: http://research.microso...