JS Basic Function-Object-Oriented Programming

Posted by adrianpeyton on Sun, 19 May 2019 17:11:10 +0200

function

  • Definition of function
<script>
    /* Define a function
    function Function name () {
        code block
    }
    Requirement 1: Write a function to add 1 to 100
    */
   function sum(){
       var num = 0;
       for(i=1;i<=100;i++){
        num += i;
       }
       console.log(num);
   }
    /* Call functions, use functions
    Function name ();
   */
   sum();
   
   function fist(){
       var a = 0;
       for(j=50;j<=500;j++){
           a += j;
       }
       document.write(a+'<br>');
   }
// Usage function
   fist();

</script>
  • Types of functions
<script>
    function sum(){
        console.log('sum function');
    }
    sum();
    // The data type of function is function, which is a special object.
    console.log('sum The type is'+typeof sum);
    console.log('alert The type is'+typeof alert);
    console.log('document.write The type is'+typeof document.write);
    console.log('console.log The type is'+typeof console.log);
    // Functions in an object (commonly referred to as object methods)

    var dog = {
        color:'white',
        age:2,
        bark:function(){
            console.log('Wang Wang Wang');
        }
    }
    // Call functions (methods) in objects
    dog.bark();

    dog.bark();

    dog.bark();

    var drink ={
        waterType:'hot water',
        amount:'25L',
        pour:function(){
            console.log('You drink water.');
        }
    }
   
    drink.pour();

</script>
  • Function Binding Event Call
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <!-- Bind a click event and call the function through the event
        onclick:Click events
        onkeydowm:press events
    -->
    <button "sum();">Calculation</button>
    <input type="text" "sum();">
</body>
</html>
<script>
    function sum(){
        var count = 0;
        for(var i =0;i<=100;i++){
            count += i;
        }
        console.log(count);
    }
    sum();//Manual call
</script>
  • Function Binding Event Call Instance
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h3>Achieve 1-xxx Additive calculation</h3>
    <input type="text" value="" "showSum();">
    <button "sum();">Calculation</button>
    <p>1-<span id="num">xxx</span>The added result is:<span id="total">50</span></p>

</body>
<script>
    function sum(){
        /*
        Get the input node and name it $input,
        Note here that it's easy to see the tag's name in front of $and after it.
        */
        var $input = document.querySelector('input');
        // Get the value of the input box
        var num = $input.value;
        console.log(num);
        var total = 0;
        for(var i =0;i<=num;i++){
            total += i;
        }
        console.log(total);
        // Lesson: Inner HTML is followed by an equals sign, not a comma
        document.querySelector('#total').innerHTML=total;
        document.querySelector('#num').innerHTML=num;
    }
</script>
</html>
  • Parametric function
<script>
    // Parameter free function
    // function add(){
    //     var a = 10;
    //     var b = 20;
    //     var num = a+b;
    //     console.log(num);
    // }
    // add(); 


        // Parametric function
    function add(a, b) {
        var num = a + b;
        console.log(num);
    }
    add(1, 2); 



    function sum(a){
        var num = 0;
        for(var i = 1;i<=a;i++){
            num += i;
        }
        console.log(num);
    }
    sum(100);
</script>
  • Function return value
<script>
    // Function return value
    function add(a,b){
        var sum = a +b;
        // Return function return value
        return sum;
    }
    var sum = add(10,10);
    document.write(sum);


    function add2(o, p) {
            var sum = o + p;
            // When there is no return, undefined is returned by default
        }
        var sum = add2(10, 10);
        document.write(sum);   
</script>
  • Declare global variables
<script>
    /* Declare global variables
        Global variables, which can be referenced globally
    */
    var man = {
        name : 'Yong'
    }
    
</script>
  • Application of Global Variables
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <!-- Put the global variables in the head, so that the following js Only accessible 
        Code order from top to bottom
    -->
    <script src="demo5-2.js"></script>
    <script>
        // global variable
        var dog = {
            name: 'Small black'
        }
        console.log(arr);
    </script>
</head>
<body>
    
    <script>
        
        console.log(dog);
        var cat = {
            name: 'Coffee cat'
        }    
    </script>
</body>
</html>


external js
var arr = [123,4,4,5,5,56];
  • local variable
<script>
    // The variables in add(){} are local variables
    function add(){
        var a = 10;
        var b = 5; 
        var sum = a+b;
        console.log(sum);
        // Local scopes, local variables, which can be accessed
    }

    console.log(b);
    // External access is unavailable
</script>
  • Global Variables Variable Local Variables
<script>
  var a = 100; //global variable
  function cal() {
    var b = 200; //local variable
    function add() {
      var b = 300; //Local variables have to be var-added, or they are global variables even in functions.
      var c = 300; //local variable
      var sum = a + b + c;
      return sum;
    }
    var result = add();
    document.write(result);
  }
  cal(); //If you annotate vara above, you can't print the result here.
</script>

object-oriented programming

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div class="name"></div>
</body>
</html>

<script>
    /* Object-Oriented: According to the requirement, a region should be processed dynamically by js.
    Define an object to represent this area, and then wrap the dynamic methods used in this area in functions.
    Systematic programming, object. function name when method is used
    */
    // Define an object named home
    var home = {
        // Define a function named fist to store the code for the implementation of the function
        // Here you need the function name: function(){}, or it will report an error.
        fist:function(){
            // Add the function of arithmetic to the name tag
            var a = 1;
            var b = 2;
            var sum = a+b;
            document.querySelector('.name').innerHTML=sum;
        }
    }
    //Then you can call it directly if you want to implement this function.
    home.fist();
    /*
    The advantage of object-oriented programming is that defining the name of the object is easy to distinguish which object this function is applied to.
    Then all the functions to be used by the object are placed in the object in the form of functions.
    Then you just need to refer to the function in the object when you refer to it.
    Benefits of easy management functions, easy to call functions
    Make programming process (routinization)
    */
</script>

Outline - Summary

(1) Definition and function of function
 1. Encapsulate multi-line statements for reuse
2. Type: function, a special type in an object

(2) Calling Method of Function
 1. Manual call   
2. Binding an event call

(3) Transfer parameters of functions (conditions)

(4) Function return value
 1. Return the result of the calculation using return
 2. No return is written and undefined is returned by default.

(5) Scope
 1. What is scope
    What works in a region becomes a scope.
2. Global scope, the variables declared in global scope are global variables, and the variables declared in script tag (sublevel) are global variables.
    /* self-summary: through global variables can facilitate the processing of js code, global variables can be placed in
    Heads are arranged in sequence. (Similar to this one used in a box office project, the code for background data is a global variable
    It can be placed on the body of home.html, so that the code block in the home.js file can be well managed.)*/
3. Local scopes and local variables
    // A function is a local scope in which variables are local variables.
    a. Variables that can be accessed from the outside of the function within the function
    b. Variables inside a function are not accessible outside the function
    c. Linking multiple scopes as use domain chains
    d. No block-level scopes (scopes are distinguished by functions)

(6). Object-Oriented Programming
 Definition: Object-Oriented: A region is dynamically processed by js according to its requirements.
    Define an object to represent this area, and then wrap the dynamic methods used in this area in functions.
    Systematic programming, object. function name when method is used
 Function: The advantage of object-oriented programming is that defining the name of an object is easy to distinguish which object this function is applied to.
    Then all the functions to be used by the object are placed in the object in the form of functions.
    Then you just need to refer to the function in the object when you refer to it.
    Benefits of easy management functions, easy to call functions
    Make programming process (routinization)
    Function formats in objects:
        Function name: function(){
            
        }

    Order of Object-Oriented Programming: Create Objects - > Define Function Method Name for Obtaining Background Data - > Define Function Name for Requirements - > Refer Background Data to Achieve the desired effect
    The whole program is programmed around the object created.

Note. Variables in functions are created indefinitely, named according to what is stored, and then referred to
  The format is ${variable name}.
  Although the code in html does not work well after it is referenced to js, it remains on the html page.
  It prevents you from having a reference when you want to change your code later.
  A local variable is a variable declared with var in a function, if it is not declared with var in a function.
  So that variable, although in the function, is a global variable, which will affect the same local variable later.
  The path parameter is added after the path, and then the variable name = value of the passed parameter is written.
  That's http//: baidu.com? Username = fanyong&age = 20
  Where & is a symbol that connects other parameters
  Suddenly I think of the problem of finding the variable name I want to pass in. According to the data table passed in from the background,
  Find a corresponding variable to see clearly the corresponding object or array, to specify the corresponding below.
  No error, the name of the contact object after the attribute (array) under the object. The attribute (object) after the attribute array.
   Array name [corresponding attribute name]. Attention should be paid to the attribute name, which can be a number or a word.
   Write in the corresponding

Topics: Programming Attribute IE