fa 1. Function definition
A function is also an object. Some functions (codes) can be encapsulated in the function and executed when necessary. Some codes can be saved in the function and called when necessary. Function will be returned when typeof is used to check a function object.
2. Function creation:
1. Create a function object and pass the code to be encapsulated to the constructor in the form of string.
var fun = new Function("console.log('Hello This is my first function');");
Calling functions: Syntax: function object ()
2. Create a function using the {function declaration}
* Create a function using a function declaration * Syntax: * function Function name([Formal parameter 1,Formal parameter 2...Formal parameter N]){ * sentence... * }
3. Create a function by using the function expression {
* var Function name = function([Formal parameter 1,Formal parameter 2...Formal parameter N]){ * sentence.... * }
4. Create objects using factory methods
/* * Create objects using factory methods * This method can create objects in large quantities */ function createPerson(name , age ,gender){ //Create a new object var obj = new Object(); //Adding attributes to an object obj.name = name; obj.age = age; obj.gender = gender; obj.sayName = function(){ alert(this.name); }; //Return the new object return obj; }
3. Parameters of function
Formal parameter: one or more formal parameters (formal parameters) can be specified in () of the function. Multiple formal parameters are separated. Declaring a formal parameter is equivalent to declaring a corresponding variable inside the function, but does not assign a value.
Argument: when calling a function, you can specify an argument (actual parameter) in (), which will be assigned to the corresponding formal parameter in the function.
When calling a function, the parser will not check the type of the argument, so pay attention to whether it is possible to receive illegal parameters. If possible, you need to check the type of the parameters. The arguments of a function can be any data type.
When calling a function, the parser does not check the number of arguments, and redundant arguments are not assigned. If the number of arguments is less than the number of formal parameters, formal parameters without corresponding arguments will be undefined
function sum(a,b){ console.log("a = "+a); console.log("b = "+b); console.log(a+b); } sum(123,"hello"); 123hello sum(true , false); 1 sum(123,456,"hello",true,null); 579 sum(123); NaN
4 function return value
You can use return to set the return value of the function. The value after return will be returned as the execution result of the function. You can define a variable to receive the result. In the function, the statement after return will not be executed. If the return statement is not followed by any value, it is equivalent to returning an undefined. Return can be followed by any type of value. The return value can also be a function.
//Call function //The value of the variable result is the execution result of the function //The value of result returned by the function is what it is var result = sum(4,7,8); //var result = alert("hello"); console.log("result = "+result);
function fun3(){ //Declare another function inside the function function fun4(){ alert("I am fun4"); } //Returns the fun4 function object as a return value return fun4; } a = fun3(); //console.log(a); //a(); fun3()();
5 execute function immediately
After the function is defined, it is called immediately. This function is called immediate execution function. The immediate execution function often executes only once.
(function(){ alert("I am an anonymous function~~~"); })(); (function(a,b){ console.log("a = "+a); console.log("b = "+b); })(123,456);
6. Function of object
A function can also be called the attribute of an object. If a function is saved as the attribute of an object, we call it the method of the object. Calling this function is called the method of the object.
var obj2 = { name:"Zhu Bajie", age:18, sayName:function(){ console.log(obj2.name); } }; obj2.sayName();
7. Enumerate the properties in the object
for... The in statement has several attributes in the object, and the loop body will execute several times. Each time, the name of an attribute in the object will be assigned to the variable.
var obj = { name:"Sun WuKong", age:18, gender:"male", address:"Huaguo Mountain" }; for(var n in obj){ console.log("Attribute name:"+n); console.log("Attribute value:"+obj[n]); }
8. Scope
Scope refers to the scope of a variable. There are two scopes in JS
Global scope:
The JS code written directly in the script tag is in the global scope The global scope is created when the page is opened and destroyed when the page is closed. There is a global object window in the global scope, which represents a browser window. It is created by the browser and we can use it directly
The created variables will be saved as the properties of the window object, and the created functions will be saved as the methods of the window object. The variables in the global scope are global variables, which can be accessed in any part of the page
Declaration of variables:
Variables declared with the var keyword will be declared before all code execution (but will not be assigned). However, if the var keyword is not used when declaring variables, the variables will not be declared in advance
Declaration of function:
Function function function ({}) created in function declaration form is created before all code is executed, so we can call function before function declaration, function var fun = funtion() created by function expression, and it will not be advanced by voice, so it can not be called before declaration.
//The function declaration will be created in advance function fun(){ console.log("I am a fun function"); } //Function expressions are not created in advance var fun2 = function(){ console.log("I am fun2 function"); }; fun2();
Function scope:
- The function scope is created when calling the function. After the function is executed, the function scope is destroyed
- Each time a function is called, a new function scope will be created, which are independent of each other
- Variables in the global scope can be accessed in the function scope
- The variable of the function scope cannot be accessed in the global scope
- When a variable is operated in the function scope, it will first look for it in its own scope. If there is one, it will be used directly. If not, it will look for it in the upper scope until the global scope is found. If it is still not found in the global scope, an error ReferenceError will be reported
- To access global variables in a function, you can use a window object The function scope also has the feature of declaration in advance
- The default is global without var declaration.
//Create a variable var a = 10; function fun(){ var a = "I am fun Variables in functions a"; var b = 20; console.log("a = "+a); function fun2(){ console.log("a = "+window.a); } fun2(); } // fun(); console.log("b = "+b); // Uncaught ReferenceError: b is not defined
function fun3(){ fun4(); // console.log(a); var a = 35; function fun4(){ alert("I'm fun4"); } } fun3();
9. debug
Firefox and chrome
10. this
Every time the parser calls a function, it will pass an implicit parameter into the function. This implicit parameter is this. This refers to an object, which is called the context object of function execution.
this will point to different objects according to different function calling methods:
1. When called as a function, this is always window
2. When called as a method, this is the object that calls the method
function fun(){ //console.log("a = "+a+", b = "+b); console.log(this.name); } fun(); // winodw //Create an object var obj = { name:"Sun WuKong", sayName:fun }; obj.sayName(); // obj
11. Constructor
Create a constructor specially used to create a Person object. The constructor is an ordinary function. The creation method is no different from that of an ordinary function. The difference is that the constructor is used to capitalize the initial letter. The difference between the constructor and an ordinary function is the caller's method. An ordinary function is called directly, and the constructor needs to be called with the new keyword.
Execution process of constructor:
1. Create a new object now
2. Set the newly created object as this in the function. You can use this in the constructor to reference the newly created object
3. Execute the code in the function line by line
4. Returns the newly created object as a return value
* an object created with the same constructor is called a class object, and a constructor is also called a class.
The object we will create through a constructor is called an instance of the class
this situation:
1. When called as a function, this is window
2. When called in the form of a method, who calls the method this is who
3. When called as a constructor, this is the newly created object
Use instanceof to check whether an object is an instance of a class:
Syntax:
Object {instanceof} constructor. If yes, it returns true; otherwise, it returns false. All objects are descendants of object,
Therefore, true will be returned when any Object and Object left instanceof are checked.
//Define the sayName method in the global scope /* * Defining functions in the global scope pollutes the namespace of the global scope * And the definition is not safe in the global scope */ /*function fun(){ alert("Hello Hello, I am: "+ this.name); };*/
12. Prototype object
prototype
For each function we create, the parser will add an attribute prototype to the function. This attribute corresponds to an object, which is what we call the prototype object.
If a function is called as an ordinary function, prototype has no effect. When a function is called in the form of a constructor, there will be an implicit attribute in the object it creates, pointing to the prototype object of the constructor__ proto__ To access this property, the prototype object is equivalent to a public area. All instances of the same class can access the prototype object. We can uniformly set the common contents of the object into the prototype object. When we access a property or method of an object, it will first look for it in the object itself. If there is one, it will be used directly. If there is no one, it will look for it in the prototype object. If it is found, it will be used directly
Note: when we create a constructor in the future, we can uniformly add the properties and methods shared by these objects to the prototype object of the constructor, so that each object can have these properties and methods without adding them separately or affecting the global scope.
//Add attribute a to the prototype of MyClass MyClass.prototype.a = 123; //Add a method to the prototype of MyClass MyClass.prototype.sayHello = function(){ alert("hello"); }; mc.a = "I am mc Medium a"; var mc = new MyClass(); var mc2 = new MyClass(); //Add a attribute to mc mc.a = "I am mc Medium a"; console.log(mc2.a); mc.sayHello();
Personal understanding is to temporarily extend the properties and methods of the JavaScript pt} class, which can be used later.
Note: when using in to check whether an object contains a property, if it does not exist in the object but exists in the prototype, it will also return true. You can use the object's hasOwnProperty() to check whether the object itself contains the property. This method returns true only if the object itself contains properties.
The prototype object is also an object, so it also has a prototype:
- When we use the properties or methods of an object, we will look for them in ourselves,
- If there is in itself, it can be used directly
- If not, search in the prototype object. If there is in the prototype object, use,
- If not, search the prototype of the prototype until the prototype of the Object object is found,
- The prototype of the Object object does not have a prototype. If it is still not found in the Object prototype, it returns undefined
-
12 tostring
When we print an object directly on the page, the event is the return value of the toString() method of the output object
//When we print an object directly on the page, the event is the return value of the toString() method of the output object //If we want to output an object without outputting [object Object], we can add a toString() method to the object //Person[name = Monkey King, age=18,gender = male] /*per.toString = function(){ return "Person[name="+this.name+",age="+this.age+",gender="+this.gender+"]"; };*/
/ / if we want to output an Object without outputting [Object] Object, we can add a toString() method for the Object
/ / Person[name = Monkey King, age=18,gender = male]
13. toSring()
14. GC garbage collection
Just like garbage will be generated when people live for a long time, garbage will also be generated during program operation. After too much garbage is accumulated, it will lead to too slow program operation. Therefore, we need a garbage collection mechanism to deal with the garbage generated during program operation. When an object has no variables or attributes to reference it, At this time, we will never be able to operate the object. At this time, this object is garbage. Too many objects will occupy a lot of memory space, resulting in slow program operation. Therefore, this garbage must be cleaned up.
There is an automatic garbage collection mechanism in JS, which will automatically destroy these garbage objects from memory. We don't need and can't garbage collection. All we need to do is set the objects that are no longer used to null