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

How to insert 10 million records into a MySQL database table in 88 seconds

The database I use is MySQL database version 5.7 ...

MySQL Server 8.0.13.0 Installation Tutorial with Pictures and Text

Install 8.0.13 based on MySQL 6.1.3. MySQL 8.0.13...

WeChat applet picker multi-column selector (mode = multiSelector)

Table of contents 1. Effect diagram (multiple col...

Example code for implementing hollowing effect with CSS

Effect principle Mainly use CSS gradient to achie...

mysql5.6.8 source code installation process

Kernel: [root@opop ~]# cat /etc/centos-release Ce...

How to delete node_modules and reinstall

Table of contents Step 1: Install node_modules in...

Vue uses echarts to draw an organizational chart

Yesterday, I wrote a blog about the circular prog...

The latest version of MySQL5.7.19 decompression version installation guide

MySQL version: MySQL Community Edition (GPL) ----...

HTML tag dl dt dd usage instructions

Basic structure: Copy code The code is as follows:...

Why I recommend Nginx as a backend server proxy (reason analysis)

1. Introduction Our real servers should not be di...

Steps to install superset under win10 system

Superset is a lightweight self-service BI framewo...

How to start and stop SpringBoot jar program deployment shell script in Linux

Without further ado, let me give you the code. Th...

How to build Jenkins+Maven+Git continuous integration environment on CentOS7

This article takes the deployment of Spring boot ...

Native js implementation of slider interval component

This article example shares the specific code of ...