inheritance

Review: Object-oriented characteristics

  • inheritance
  • encapsulation
  • Polymorphism (abstract)

Inheritance between objects

  • Inheritance refers to: types and between types

Copy the object

  • for… In: Copies the attributes of the parent object to the child object
var laoli = {
    name:"laoli".age:55.house:"Villa"
};
var xiaoli = {
    name:"xiaoli".age:23
}
// Copy the attributes of the parent object to the child object
// Encapsulates a function inherited between objects
function extend(parent,child){
    for(var k in parent){
        // Attributes of children do not need to be inherited, such as the name of the child object
        if(child[k]){
            continue; } child[k] = parent[k]; }}// Call the wrapped inheritance function
extend(laoli,xiaoli);
console.log(xiaoli); // Succeeded in inheriting
Copy the code

Constructor property inheritance

  • Borrow constructors (using the call method)
function Person(name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;

function Student(name,age,sex,score){
    // Call the parent constructor
    Person.call(this,name,age,sex);
    this.score = score;
}
// Create an instance object
var stu = new Student("ww".12."Female".99);
console.dir(stu);
console.log(stu.name);
Copy the code

Constructor’s prototype method inheritance

  • Copy inheritance (for — in)
function Person(name,age,sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    // The parent prototype method
    Person.prototype.sayHi = function (){
        console.log("Hello");
    }
    function Student(name,age,sex,score){
        // Call the parent constructor
        Person.call(this,name,age,sex);
        this.score = score;
    }
    // When using the copy method to traverse, pay attention to constructor
    // Subclass prototype objects iterate over their parent class prototype objects
    for(var k in Person.prototype){
        if(k === "constructor") {continue;
        }
        Student.prototype[k] = Person.prototype[k];
        }
        // Create a student instance object
        // Solve the problem caused by previous prototype inheritance: new Person() is passed as a one-time argument
        var stu = new Student("ff".23."Female".67);
        stu.sayHi();
Copy the code
  • Prototype inheritance
function Person(name,age,sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    // The parent prototype method
    Person.prototype.sayHi = function (){
        console.log("Hello");
    }
    function Student(name,age,sex,score){
        // Call the parent constructor
        Person.call(this,name,age,sex);
        this.score = score;
    }
    // When using the copy method to traverse, pay attention to constructor
    // Subclass prototype objects iterate over their parent class prototype objects
    // Create a student instance object
    // Solve the problem caused by the previous prototype inheritance: new Person(the argument passed is one-time
    
    // Method 2: Prototype inheritance
    Student.prototype = new Person();
    Student.prototype.constructor = Student;
    var stu = new Student("ff".23."Female".67);
    stu.sayHi();
Copy the code

Combination of inheritance

  • Attributes: inherited inside the constructor
  • Method: Through prototype inheritance
function Person(name,age,sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    // The parent prototype method
    Person.prototype.sayHi = function (){
        console.log("Hello");
    }
    function Student(name,age,sex,score){
        // Attribute inheritance: call the parent constructor
        Person.call(this,name,age,sex);
        this.score = score;
    }
    // When using the copy method to traverse, pay attention to constructor
    // Subclass prototype objects iterate over their parent class prototype objects
    // Create a student instance object
    // Solve the problem caused by the previous prototype inheritance: new Person(the argument passed is one-time
    
    // Method inheritance: prototype inheritance
    Student.prototype = new Person();
    Student.prototype.constructor = Student;
    var stu = new Student("ff".23."Female".67);
    stu.sayHi();
Copy the code

The way a function is defined

  • Recommendation: Define a function as a function declaration

Function declaration

// Function declaration
function fn (){
    console.log("fn");
}
Copy the code

Functional expression

// Function expression
var fun = function (){
    console.log("fun");
}
Copy the code

new Function

  • Not recommended: Its performance is relatively low, js in the execution, the first to parse the entire string, and then analyze the end of the statement position, before execution.
// new function: The argument is a string and the statement is written in the same way as usual
var func = new Function('var a = "1"; console.log(a)');
Copy the code

Note (compatibility issues exist) :

  • If you write fn() at the end, the higher version will print true because it is a function declaration, not a variable.
  • The lower version, regardless of whether if is true or false, will only print false because it recognizes only the function that was last defined.
  • The code shown
/ In older browsers, an error is reported// That is, variable declarations are improved in older browsers
// In IE8 earlier browsers, function declaration enhancements are implemented
fn();
// The function in the if statement is promoted
if(true) {function fn (){
        console.log("true"); }}else {
    function fn (){
        console.log("false"); }}Copy the code

The difference between function declarations and function expressions

  • Does the function have a name
    • Function declaration: Must have a name
    • Function expressions: Can have no name, such as anonymous functions
  • Preresolution stage
    • Function declaration: the function will be promoted, created in the pre-parsing phase, can be called before and after the declaration.
    • Function expression: Similar to variable assignment. There is no function promotion, which is created at execution time and can only be called after the expression is executed.

Functions are objects

  • A function is itself an object that can be defined through a constructor method and calls properties and methods.
// new function: The argument is a string and the statement is written in the same way as usual
var func = new Function('var a = "1"; console.log(a)');
Copy the code

Function calls and this

The calling method of a function

Common function

// A normal function
function fn (){
    console.log("Hi");
}
// Call the normal method
fn();
Copy the code

The constructor

// constructor
    function Person(name){
        this.name = name;
    }
    // Create an instance object to call
    var p = new Person("zs"); sCopy the code

Object methods

// Object method
    var o = {
        sayName : function (){
            console.log("wm"); }}// Call the method
    o.sayName();
Copy the code

Event functions

// Event function: called when the event is triggered
    document.onclick = function (){
        alert("Hello");
    }
Copy the code

Timer, delay function

// Timer, delay timer method
    setInterval(function (){
        console.log("wa");
    },1000);
    setTimeout(function (){
        console.log("timeout");
    },1000);
Copy the code

The different scenarios that this points to within the function

  • Normal functions: Internal this points to window by default
  • Constructor: The inner this points to the instance object to be created in the future
    • This is also an instance object in the prototype method
  • Object methods: The internal this defaults to referring to the calling object itself
  • Event function: Points to the event source that triggers the event function
  • Timers, delayers: By default internal this points to window
  • Note:The reference to this is not deterministic at first, but needs to be checked in context
    • The following code:
      // A normal function
            function fn (){
                console.log(this);
            }
      
            // Object method
            var o = {
                sayName : function (){
                    console.log("wm");
                },
                fun : fn
            }
            // This refers to the o object
            // This is no longer window in normal functions
        o.fun();
      Copy the code

Call, apply, bind methods

  • This has its own default reference when called from inside the function. But you can change the direction of this in three ways.

Call method

  • Function:
    • Specifies this inside the function
    • Functions can be executed and arguments passed
  • The call() method calls a function with a specified this value and separately supplied arguments (a list of arguments).
  • Note: This method works like apply() except that call() takes a list of arguments, while apply() takes an array of arguments.
  • Grammar:
    fun.call(this,arg1,arg2);
    Copy the code
    • This: Specifies this value when fun is run
    • If null or undefined the internal this points to the window.
    • Show the code
      function fun (a,b){
              console.log(this);
              console.log(a + b);
          }
          var o = {
              name : "zs"
          }
          // Call method: change the this pointer inside a normal function
          // Function: 1. Change this pointer inside the function
          // 2. Execute the function and pass the parameter
          // Return value: the function's own return value
          fun.call(o,1.2); / / 3
          console.log(o);
      Copy the code

The apply method

  • The apply() method calls a function with a specified this value as the first argument and an array (or array-like object) as the second argument.
  • Note: This method works like the call() method, except that the call() method takes a list of arguments, while the apply() method takes an array of arguments.
  • Grammar:
fun.apply(thisArg, [argsArray])
Copy the code
  • Demo code
function fun (a,b){
    console.log(this);
    console.log(a + b);
}
var o = {
    name : "zs"
}

/ / the apply method
// Function: 1. Specify this inside the function
// 2. You can execute the function and pass the parameter
fun.apply(o,[4.8]); / / 12
Copy the code

The bind method

  • The bind() function creates a new function (called a binding function) that has the same function body (the call attribute built into the ECMAScript 5 specification) as the called function (the target function of the binding function).
  • parameter
    • ThisArg: this parameter is referred to as this when the original function is run when the binding function is called. This parameter is invalid when a binding function is called using the new operator.
    • arg1, arg2, … When the binding function is called, these arguments are passed to the bound method before the arguments.
  • Return value: Returns a copy of the original function modified with the specified this value and initialization parameters.
  • Demo code
function fun (a,b){
            console.log(this);
            console.log(a + b);
        }
        var o = {
            name : "zs"
        }
        / / the bind function
        // Function: 1. Specify the function this
        // 2. Cannot execute function, but can pass parameter
        var fn = fun.bind(o,1.34); // Bind the function
        // Bind was not executed after the call
        ƒ fun (a,b){console.log(this); console.log(a + b); } * /
        console.log(fn);
        fn(); // The function is executed (without passing arguments) with output 35
        // If the function is executed, the parameter is passed.
        fn(6.8);  // The output is still 35
Copy the code
  • Pass parameters separately, code demonstration
function fun (a,b,c,d){
    console.log(this);
    console.log(a + b + c + d);
}
var o = {
    name : "zs"
}
/ / the bind function
// Function: 1. Specify the function this
// 2. Cannot execute function, but can pass parameter
var fn = fun.bind(o,1.34);
console.log(fn);
fn(5.3); // Output: 43
Copy the code

Application of call, apply, and bind methods

Application of the Call method

  • The call application borrows methods that objects don’t have
  • Demo code
// Call method application
    var arr = [1.5.6.7];
    // arr.push(8);
    // console.log(arr);
    // But objects like arrays do not have push methods
    var o = {
      0:1.1:5.2:7.length:3  
    };
    // How to implement array-like object push
    // Just find the push function and change this inside it to our array object
    Array.prototype.push.call(o,7);
    console.log(o); // Length automatically changes to 4
Copy the code

The application of the apply method

  • Methods that are not in the array can be expanded using apply before proceeding to the next step.
  • Demo code
// the apply method is applied
    // Define an array that can be broken up using the apply method
    var arr = [1.8.4.7];
    // Want to borrow some of the methods that are now built into JS
    / / the console log (Math. Max,4,6,7,9,3 (1));
    console.log(Math.max(arr)); // NaN
    // So you can borrow the apply method, which splits the parameters
    var maxX = Math.max.apply(Math,arr);
    console.log(maxX); / / 8
Copy the code
  • Note: math.max. apply(Math,arr) specifies the first argument to apply, either null or Math.
  • Demo Code 2
var arr = [1.8.4.7];
console.log(1.5.7.34); / / 1,5,7,34
// The output is an array
console.log(arr); / /,8,4,7 [1]
// You can expand the array by calling apply
console.log.apply(null,arr); // 1 8 4 7
Copy the code

Application of the bind method

  • For functions that need to be bound, but not executed immediately.
  • Demo Code 1
// The bind method is applied
var o = {
    name : "zs".age : 13.s : function (){
        // This is window by default, and window has no ag property at all
        setInterval(function (){
            console.log(this.age);
        }.bind(this),1000); }};// When we bind the o object using the bind method, we can print O.age
  o.s(); // this = o
Copy the code
  • Demo Code 2
document.onclick = function (){
    console.log(this);
} // Output: this = #document
// // NOW I want to change this inside the event function, but I don't want it to be executed immediately
document.onclick = function (){
    console.log(this);
}.bind(o); 
Copy the code

conclusion

The Call and Apply features are identical

  • Similarities:
    • 1. Both are used to call functions, and immediately
    • 2. You can specify this as the first argument when calling a function.
  • Difference:
    • When a call is called, the arguments must be passed as a list of arguments, that is, in comma-separated order.
    • When apply calls, the parameters must be an array, and when executed, the elements inside the array are taken out one by one, passing them along with the corresponding parameters.
  • Note: If the first argument is specified as null or undefined, the inner this points to the window
var arr = [5.9.3.7];
// All four statements output the same result
// Output: 5 9 3 7
console.log.apply(null,arr);
console.log.apply(window,arr);
console.log.apply(console,arr);
console.log.apply(window.console,arr);
Copy the code

The bind method

  • Can be used to specify the pointer to this inside, and then generate a new function that changes the pointer to this
  • Differences: The biggest difference between call and apply is that bind does not call
  • Bind supports passing parameters in a special way: there are two places to pass parameters
    • 1. Pass as a list of arguments along with bind
    • 2. When called, it is passed as a parameter list
  • So what happens when you bind or what happens when you call it?
    • The two are merged: the arguments passed by bind and the arguments passed by call are merged and passed inside the function.

Other members of the function

Arguments collection of arguments

  • In practice, a arguments keyword is used directly inside the function
  • An array-like object that stores all of the arguments passed in when a function is called.
  • Be flexible with arguments class array objects
    • Since the transmission parameters are not fixed and cannot be determined by ABCD, this method can be used for production.
    • Demo codejs function max(){ var nowMax = arguments[0]; for(var i = 0; i < arguments.length; i++){ if(arguments[i] > nowMax){ nowMax = arguments[i]; } } return nowMax; }

The arguments.callee function itself,a property of arguments

Arguments. length Number of arguments

If the caller of the fn. Caller function is called globally, the caller is null

  • The caller is the scope in which the function is called

Fn. length Specifies the number of parameters

Fn. name Specifies the name of the function

  • Demo code
function fn(a,b){
    // Set of arguments
    console.log(fn.arguments); / / the Arguments (2) [1, 2, 3, 4]
    // The caller of this function, if called globally, returns null
    console.log(fn.caller); // null
    // The number of parameters
    console.log(fn.length); / / 2
    / / the function name
    console.log(fn.name); // fn
    console.log(fn.arguments.callee); // The function itself
}
fn(1.2.3.4);
Copy the code

Higher-order functions

Functions can be arguments

// Higher order function
// Timer/delay is also a higher-order function
Function as an argument to another function
// Example: Watch a movie after dinner
function eat(movie){
    console.log("After dinner");
    movie();
}
function movie (){
    console.log("Go to the movies");
}
eat(movie);
Copy the code

A function can be a return value

Function as the return value of another function
function outer(n){
    return function inner(m){
        console.log(m + n); }}var fun = outer(100);
fun(8); / / 108
fun(18); / / 118
Copy the code

A function closure

Retrospective scope, scope chain, pre-resolution

  • Brush up on
    • Scope chain: when a variable is used, it is searched from its own scope first. If there is no definition of the variable in the current layer, it is searched from this layer until the first definition of the variable is found. (If no definition is found, the console displays an error is no defined.)
    • Overshadowing effect: The nearest one overshadows the far one
  • Global scope
  • Function scope
  • There is no block-level scope
  • Inner scopes can access outer scopes, but not vice versa

What is a closure

  • Closures allow you to access the scope of an outer function within an inner function. In JS, every time a function is created, the closure is created at the same time the function is created.

closure

  • A function definition naturally remembers its generated scoped environment and the function itself, forming a closed environment called a closure. No matter how or where a function is called, it returns to the closed environment in which it was defined.
  • The following figure

Observe the closure

  • In general, a globally defined function is also a closure, but there is no way to call such a function out of scope to observe the characteristics of a closure.
  • Closures exist naturally and do not require additional structures. However, in order to observe the characteristics of closures, we need to use some special structures to call the child functions inside a parent function outside the parent function, so as to observe the existence of closures.
  • Demo code
// Experience closures
// Take an inner function outside the parent function and see if the parent variable can still be called
function outer (){
    var a = 10;
    // use inner as the return value -> higher-order functions
    return function inner (){
        console.log(a);
    };
}
// Outside outer, the a variable cannot be accessed directly
console.log(a);
var out = outer();
// call the function, output result 10
// Call out globally, which should look for the global a variable
// But the real output is 10, from the variable inside outer
out();
Copy the code

The purpose of closures

  • Function members can be read outside a function
  • Keeps function members alive in memory at all times
function outer(n){
    return function inner(m){
        console.log(n + m); }}var out = outer(100);
// Can be repeated multiple times
out(4); / / 104
out(7); / / 107
out(45); / / 145
Copy the code

Closure problems

  • Solution: close scope with self – calling function, reduce scope scope
// Closure issues
var arr = [];
for(var i = 0; i <=10; i++){
    // Solution:
    // Close the scope with a self-calling function to reduce the scope
    (function (i){
        arr[i] = function (){
        console.log(i);
    }
    })(i);          
}
// Purpose: To call the corresponding item of the array and print its corresponding subscript
// All outputs are 11
// I = 11
// After adding the self-calling function, the output becomes: 0 1
arr[0] (); arr[1] ();Copy the code

supplement

  • Console break point mode (and scope can be viewed by scope)