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

Detailed explanation of the process of building an MQTT server using Docker

1. Pull the image docker pull registry.cn-hangzho...

A quick guide to Docker

Docker provides a way to automatically deploy sof...

The difference between MySQL database host 127.0.0.1 and localhost

Many of my friends may encounter a problem and do...

Detailed explanation of the steps to build a Vue project with Vue-cli

First you need to install Vue-cli: npm install -g...

Detailed explanation of CSS image splicing technology (sprite image)

CSS image splicing technology 1. Image stitching ...

Vue plugin error: Vue.js is detected on this page. Problem solved

Vue plugin reports an error: Vue.js is detected o...

Solution to the same IP after cloning Ubuntu 18 virtual machine

Preface I recently used a virtual machine to inst...

Remote Desktop Connection between Windows and Linux

When it comes to remote desktop connection to Lin...

Some methods to optimize query speed when MySQL processes massive data

In the actual projects I participated in, I found...

Detailed explanation of MySQL backup process using Xtrabackup

Table of contents 01 Background 02 Introduction 0...

Detailed explanation of Excel parsing and exporting based on Vue

Table of contents Preface Basic Introduction Code...

How to build a complete samba server in Linux (centos version)

Preface smb is the name of a protocol that can be...