javascript functions and objects

Preface

This study is about functions and objects. Functions should be familiar to you. You have already been exposed to mathematics when you were in school. However, although they are both functions, they are different. One is a formula and the other is a code. Then it What possibilities can it bring? Let me show you its charm! What is the object? Everything is an object. The objects in life are vivid. Of course, this object is also

Not bad.

1. JS functions and applications

1. The concept of function


In JS, a lot of the same code or codes with similar functions may be defined, and these codes may need to be reused in large quantities.
Although the for loop statement can also implement some simple repeated operations, it is more limited. At this time, we can use functions in JS.

2. Use of functions


There are two steps when using a function: declaring the function and calling the function.

Declare function

  function function name(){};
call function

  • Function name(); // Execute the function body code by calling the function name
  • Don’t forget to add parentheses when calling
  • Tip: If the function is not called, it will not be executed by itself.
  • Note: Declaring a function itself does not execute code. The function body code is only executed when the function is called.

3. Function parameters


3.1 Formal parameters and actual parameters
When declaring a function, you can add some parameters in parentheses after the function name. These parameters are called formal parameters. When calling the function, you also need to pass the corresponding parameters. These parameters are called called actual parameters.
Parameter Description
Formal parameters The parameters passed when the formal parameter function is defined are not currently known.
Actual parameters The actual parameters passed when the parameter function is called. The actual parameters are passed to the formal parameters.

The role of parameters: Certain values ​​cannot be fixed inside the function. We can pass different values ​​into the function when calling the function through parameters.

3.2 The problem of mismatch between the
number of function formal parameters and actual parameters Number of parameters Description The
number of actual parameters is equal to the number of formal parameters. The correct result is output. The
number of actual parameters is more than the number of formal parameters. Only the number of formal parameters is obtained and the number of
actual parameters is less than Formal parameters with a large number of formal parameters are set to undefined, and the result is NaN.

3.3 Summary
● Functions can take parameters or not.
● When declaring a function, the formal parameters are in the brackets of the function name. The default value of the formal parameters is undefined. ●
When calling a function, the actual parameters are in the brackets of the function name.
● Many Separate the parameters with commas
. The number of formal parameters does not need to match the number of actual parameters, but the results are unpredictable. We try to match four.

4. Return value of function


4.1 return statement
Sometimes, we want the function to return the value to the caller. This can be achieved by using the return statement.

(1) Our function only implements a certain function, and the final result needs to be returned to the caller of the function. The function name () is implemented by return. (
2) As long as the function encounters return, the subsequent result will be returned to the caller of the function. name() = the result after return

4.2 return terminates the function.
The code after the return statement is not executed.

4.3 Functions without return return undefined.
All functions have a return value.
1. If there is a return, the value after return is returned.
2. If there is no return, undefined is returned.

4.4 The difference between break, continue and return
, break: end the current loop body (such as for. while)
●continue: jump out of this loop and continue to execute the next loop (such as for. while)
●return: not only can exit the loop, but also It can return the value in the return statement and also end the code in the current function body.

5. Case of odd average value

 <title>奇数平均值</title>
    <script>
        var arr = [1, 2, 3, 4, 5, 6, 7];
        var average = [];
        var sum = 0;
        var aa = 0;

        function getjishu() {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] % 2 != 0) {
                    sum += arr[i];
                    average[average.length] = arr[i];
                }

            }
            aa = sum / average.length;
            return aa;

        }
        console.log(getjishu());
    </script>

2. JavaScript scope and pre-parsing

1. Use of arguments


When we are not sure how many parameters are passed, we can use arguments to get them. In JavaScript, arguments is actually a built-in object of the current function. All functions have a built-in arguments object, which stores all the actual parameters passed.

The arguments display form is a pseudo array, so it can be traversed. Pseudo arrays have the following characteristics:

  • Has length attribute
  • Store data by index
  • Push, pop and other methods without arrays

Only functions have arguments objects, and each function has built-in arguments.

Functions can call another function.
Because each function is an independent block of code used to complete special tasks, functions often call each other.

2. Two ways to declare functions


 1. Use the function keyword to customize the function (named function)
function fn() { } fn();  2. Function expression (anonymous function) var variable name = funttion() {}; var fun = function(aru) { console.1og("I am a function expression' ); console. log(aru); fun( 'Teacher pink); (1) fun is the name of a variable, not a function name  (2) The way to declare a function expression is similar to that of a variable. It’s just that variables store values, while function expressions store functions  (3) Function expressions can also pass parameters.










 
3. Scope overview


The use of scope improves the locality of program logic, enhances program reliability, and reduces name conflicts.

  1. JavaScript scope: It is the code name (variable) that works and works within a certain scope. The purpose is to improve the reliability of the program, and the important thing is to reduce naming conflicts.
 2. The scope of js: global scope local scope
3. Global scope: the entire script tag or a single js file
var num = 10;
console.1og(num);
4. local scope (function scope ) is the local scope inside the function. The name of this code only has effects and functions inside the function
function fn() { //local scope varnum=20; console.1og(num); } fn();




4. Scope chain

When an internal function accesses the variables of an external function, it uses a chain search method to determine which value to take. This structure is called a
scope chain. The principle of proximity means searching upwards layer by layer.
 

var num = 10;
function fn() { //外部函数
var num = 20: 
function fun() { //内部函数
console.1og(num); 
}
fun();
}
fn();

●As long as it is code, there is at least one scope
●The local scope written inside the function
●If there are functions in the function, then another scope can be born in this scope
●According to the internal function, the outside can be accessed This mechanism of function variables, which uses chained lookup to determine which data can be accessed by internal functions, is called a scope chain.

5. Pre-analysis

1. Our js engine runs js in two steps:
pre-parsing and code execution 
(1). The pre-parsing js engine will promote all vars
and functions in js to the front of the current scope
 (2). Code execution follows the code The order of writing is executed from top to bottom
 2. Pre-parsing is divided into variable pre-parsing (variable promotion) and function pre-parsing (function promotion)
(1) Variable promotion means that all variable declarations are promoted to the front of the current scope without promotion. Assignment operation
(2) function promotion is to promote all function declarations to the front of the current scope without calling the function

6. Case of determining the number of days in February

  <title>判断二月份的天数</title>
    <script>
        function getrui(year) {
            var flag = false;
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
                flag = true;
            }
            return flag;
        }

        function backDay() {
            var year = prompt('请输入年份:');
            if (getrui(year)) {
                alert('当前的年份是闰年2月份有29天');
            } else {
                alert('当前的年份是平年2月份有28天');
            }
        }
        backDay();
    </script>

3. javascript object

1.What is an object?

In JavaScript, an object is an unordered collection of related properties and methods. All things are objects, such as strings, values, arrays, functions, etc.
Objects are composed of properties and methods.
●Attributes: characteristics of things. Use attributes to express in objects (common nouns)
●Methods: the behavior of things, use methods to express in objects (common verbs) The
object expression structure in js is clearer, more powerful, and more complete

2. Three ways to create objects


In JavaScript, we can currently create objects in three ways:
●Use literals to create objects
●Use new Object to create objects
●Use constructors to create objects

Summary of variables, attributes, functions, and methods.
Variables and attributes are alike in that they are used to store data.
Functions and methods are alike in that they realize a certain function and do something.

●Variables: declare and assign values ​​separately, exist alone
●Attributes: variables in an object are called attributes, do not need to be declared, and are used to describe the characteristics of the object●
Function: exist separately, and can be called through "function name 0"
● Method: The functions in the object are called methods. Methods do not need to be declared and can be called using "object method name 0". Methods are used to describe the behavior and functions of the object.

2.1 Create objects using literals


Object literal: The curly braces {} contain the properties and methods that express this specific thing (object).
 1. Use object literals to create objects {}
 

 var obj={};//创建了个空的对象
var obj={
uname: '张三疯,
age: 18,
sex: 男,
sayHi: function() {
console.1og('hi~" );
}
}

  (1) The attributes or methods inside are in the form of key-value pairs. Key attribute name: value attribute value
 (2) Multiple attributes or methods are separated by commas
 (3) The method colon is followed by an anonymous function
 

Using an object
 (1). To call the properties of an object, we take the object name. Attribute name. We understand it as
console . log(obj .uname);
  (2). There is another way to call the attribute object name ['property name']
console .1og(obj[ 'age ']); Quotation marks are required
 (3) Call the object's method sayHi
object name. Method name () Don't forget to add parentheses
obj. sayHi();|
I
use literals to create objects

  <title>对象字面量建对象</title>
    <script>
        var obj = {
            name: '可可',
            type: '阿拉斯加犬',
            age: '5岁',
            color: '棕红色',
            skill: function() {
                console.log('技能:汪汪汪,演电影');
            }
        }
        console.log(obj.name);
        console.log(obj.type);
        console.log(obj.age);
        console.log(obj.color);
        obj.skill();
    </script>

2.2 Create objects using new object
 

var obj = new Object(); //创建了-个空的对象
obj.uname = '张三疯;
obj.age = 18;
obj.sex =男;
obj.sayHi = function() {
console.1og('hi~' );
}


 (1) We use the equal sign = assignment method to add the properties and methods of the object
  (2) End each property and method with a semicolon
console.1og(obj .uname);
console .logtobj['sex']) ;
obj .sayHi();
 

 <title>new object对象</title>
    <script>
        var obj = new Object();
        obj.name = '鸣人';
        obj.sex = '男';
        obj.age = '19岁';
        obj.skill = function() {
            console.log('分身术');
        }
        console.log(obj.name);
        console.log(obj.sex);
        console.log(obj.age);
        obj.skill();
    </script>

2.3 Create objects using constructors


 The syntax format of the constructor
  function constructor name () { this. attribute = value; this. method = function () {}   }  var object name = new constructor name (actual parameter); You do not need to return to call the object constructor Return structure




 We need to use the constructor because our previous two methods of creating objects can only create one object at a time.

  •  Because we create an object at a time, many of the properties and methods inside are the same and we can only copy them.
  •  So we can use the function method to repeat these same codes. We call this function a constructor.
  •  And because this function is different, what is encapsulated in it is not ordinary code, but an object.
  •  The constructor is to abstract some of the same properties and methods in our objects and encapsulate them into functions.

Constructor: It is a special function, mainly used to initialize objects, that is, assign initial values ​​to object member variables. It is always used with the new operator. We can extract some public properties and methods from the object and encapsulate them into this function.

3. Traverse object properties


The for..in statement is used to loop through the properties of an array or object.
for (var k in obj) { console.log(k); // k variable output gets the attribute name console.1og(obj[k]); // obj[k] gets the attribute value

 <title>构造函数建对象</title>
    <script>
        function Zero(uname, type, blood, attack) {
            this.uname = uname;
            this.type = type;
            this.blood = blood;
            this.attack = attack;

        }
        var lianpo = new Zero('廉颇', '力量型', '500血量', '近战');
        console.log(lianpo.uname);
        console.log(lianpo.type);
        console.log(lianpo.blood);
        console.log(lianpo.attack);
        var houyi = new Zero('后羿', '射手型', '100血量', '远战');
        console.log(houyi.uname);
        console.log(houyi.type);
        console.log(houyi.blood);
        console.log(houyi.attack);
    </script>

4. Summary


Objects can make the code structure clearer
. Object complex data type object.
Essence: An object is an unordered collection of related properties and methods.
Constructor generally refers to a certain category. Such as Apple. Whether it's a red apple or a green apple. They are all collectively called apples.
An object instance specifically refers to a thing, such as this apple, the pink teacher who is giving you a lecture, etc.
The f.in statement is used to loop through the properties of an object.
 

Summarize

The above is some basic knowledge of functions and objects and some simple case introductions. After learning the knowledge of this function and objects, and understanding the things in them, you will feel that functions and objects can actually be explained and expressed in this way, which not only improves I gained insights and improved knowledge points that I had not learned before. I suddenly realized it, which was also a beautiful accident!

Guess you like

Origin blog.csdn.net/txq231254/article/details/123984913