Senior JavaScript

The target

  1. The prototype
  2. The prototype chain of the == function ==
  3. Prototype chain relationships between functions and objects
  4. Four ways to call a function
  5. Arrow function

2. Prototype

Store functions on the prototype

  1. Solved the same problemsayWaste of memory
  2. Solved the problem of contaminating global variables
    function createStudent(name, age) {
      this.name = name;
      this.age = age;
    }
    // Mount the global function say directly onto the constructor prototype
    // prototype is an object that every constructor has built-in. We call it a prototype
    createStudent.prototype.say = function () {
      console.log(this.name);
    }

    const obj = new createStudent("One can".83);
    const obj1 = new createStudent("One can 1".84);

    console.log(obj.say === obj1.say); // true 
Copy the code

Prototype explain

  • The prototype word isprototypeThe name of the prototype is a common name in the industry.
  • A prototype is essentially an object, understood asJavaScriptIf it’s a constructor, by default, the constructor is associated with an object. This object is called the prototype of the constructor. Members written in the prototype can be called by the instance that the constructor creates
  • The prototype isJavaScriptAutomatic help us inDefining a constructor“Was added
  • All constructor instances share a stereotype
  • The typical prototype is a mount function

graphic

3. The prototype proto

  1. Javascript states that each (constructor) function has a Prototype property that points to another object. All properties and methods of this object are inherited by instances of the constructor. This means that we can define properties and methods that all object instances need to share directly on a Prototype object so that objects of the same type can share methods or other members

  2. The __proto__ attribute of the instance is equal to the constructor’s prototype

    function Person (name, age) {
      this.name = name
      this.age = age
    }
    
    console.log(Person.prototype)
    
    Person.prototype.type = 'human'
    
    Person.prototype.sayName = function () {
      console.log(this.name)
    }
    
    var p1 = new Person(...)
    var p2 = new Person(...)
    
    console.log(p1.sayName === p2.sayName) // => true
    Copy the code
    • This is for all instancestypeProperties andsayName()Method, it’s actually the same memory address
  3. Note: Due to compatibility issues between browsers, we will only use constructor prototype

  4. The _proto_ of the instance is just for the convenience of viewing the data during development, it will not be manually modified and manipulated.

4. Prototype relationships

The relationship between constructors, instances, and stereotypes

Constructor: A constructor is a function that creates an object with new.

Instance: An object instantiated by a constructor is called an instance of the constructor. A constructor can have many instances.

Prototype: Each constructor has a property prototype, and the function’s prototype property value is the prototype. Instances created through constructors can use properties and methods directly from prototypes.

All constructors are instances of Function

Array and Person and Date are instances of Function

Function and Object

Some people say JavaScript is the product of an author who spent seven days writing it – it’s not perfect

console.log(Object.prototype===Function.prototype.__proto__)
Copy the code

What about the top of Object?

Near the top

 console.log(Object.prototype.__proto__ === null);
Copy the code

5. The prototype chain

1 the concept

Any object, there is a prototype object, the prototype object itself is an object, so the prototype object also has its own prototype object, so a link a link to form a chain structure, we call this chain structure: prototype chain.

  • Object. Prototype is the end of the prototype chain, and Object. Prototype is null.

Attribute lookup principle

If it is a fetch operation

  1. I’ll look it up on myself first, and if I don’t
  2. Depending on the__proto__Find the corresponding prototype. If not
  3. Has been foundObject.prototypeIf not, it cannot be found and an error is reported

6. Es5 prototype chain inheritance

Use the ability of code to achieve object-oriented feature encapsulation and inheritance

Early experience

  1. The subclass Strudent inherits the attributes of its parent class Person
/ / parent class
function Person(name, height) {
    this.name = name;
    this.height = height;
}

Person.prototype.say = function () {
    console.log(this.name);
    console.log(this.height);
}

/ / subclass
function Student(grade, name, height) {
    // Use the parent constructor to complete the assignment
    Person.call(this, name, height)
    this.grade = grade;
}

// Assign all attributes and methods on the superclass prototype
Student.prototype = Person.prototype;
// modify something like that
Student.prototype.constructor = Student;

// Create an instance of the subclass
const stu = new Student("One year"."Week star".170);
stu.say();
Copy the code

7. Scope and scope chain

The scope of the variable created by the let is from the creation of the let variable to the} end of the structure in which it resides

Scope: The scope in which a variable can be used after it is defined.

var num = 11;// Global variables
function fn(){
  var num1 = 22;// Local variables
  console.log(num);  // Global variables can be accessed anywhere
  console.log(num1);  
}
console.log(num);
Copy the code

There is only global scope and function scope in JS.

The scope of a function is defined when the function is defined, regardless of where the function is called.

  • We only care where the function is defined, not where the function is called
    • Define the function, and the scope of the function is determined
    • Function as a parameter, does not affect the scope of the function
var num = 123;
function f1() {
  console.log(num); / / 123
}

function f2(){
  var num = 456;
  f1();
}
f2();/ / 123
Copy the code

The scope chain

Scope chain: Any function forms a scope. If the function is nested within other functions, then the external function also has its scope, which goes all the way up to the global environment, forming a scope chain.

Search principles for variables:

  1. Starts at the current scope to find if the variable is declared, and returns its value if it is.
  2. If it doesn’t exist, it looks up the scope, and if it does, it returns.
  3. If it does not exist, go all the way to the global scope; if it does, return. An error is reported if the variable is also not found globally

Scope chain exercises

/ / 1
var num = 10;
fn1();
function fn1() {
  console.log(num);  // undefined
  var num = 20;
  console.log(num);  / / 20
}
console.log(num);    / / 10


// 2 -- Change the interview question above
var num = 10;
fn1();
function fn1() {
  console.log(num);  / / 10
  num = 20;
  console.log(num);  / / 20
}
console.log(num);    / / 20


/ / 3
var num = 123
function f1(num) {
    console.log(num) / / 456
}

function f2() {
    var num = 456
    f1(num)
}
f2()


/ / 4
var num1 = 10;
var num2 = 20;
function fn(num1) {
  num1 = 100;
  num2 = 200;
  num3 = 300;
  console.log(num1);  / / 100
  console.log(num2);  / / 200
  console.log(num3);  / / 300
  var num3;
}
fn();
console.log(num1); / / 10
console.log(num2); / / 200
console.log(num3); / / an error
Copy the code

8. This and four modes of calling functions

Depending on the direction of this inside the function, there are four call modes

  1. Function call pattern
  2. Method invocation pattern
  3. Constructor call pattern
  4. Context invocation pattern (borrowing method pattern)

Function call pattern

If a function is not a property of an object, it is called as a function. This refers to the window

function fn(){
  console.log(this);/ / points to the window
}
fn();
Copy the code

Method invocation pattern

When a function is stored as a property of an object, we call it a method. When a method is called, this is bound to the current object

const obj = {
  sayHi:function(){
    console.log(this);In the method invocation pattern, this refers to the object calling the current method.
  }
}
obj.sayHi();
Copy the code

Constructor call pattern

If the function is called with the new keyword, this is bound to the created new object.

function Person(){
  console.log(this);
}
Person();// window
var p = new Person();// person{}
Copy the code

A couple of exercises

This function is called (); // This function is called ()

/ / 1
var age = 38;
var obj = {
    age: 18.getAge: function () {
        console.log(this.age); }}var f = obj.getAge;
f();/ / 38


/ / 2
var age = 38;
var obj = {
  age:18.getAge:function () {
    console.log(this.age);/ / 18
    function foo(){
      console.log(this.age);/ / 38
    }
    foo();
  }
}
obj.getAge();


/ / 3
var length = 10

function fn() {
    console.log(this.length) / / 10
}
var obj = {
    length: 5.method: function (fn) {
        fn() 
        arguments[0] ();/ / 3
    }
}
obj.method(fn, 10.5);
Copy the code

Method borrowing pattern

Also called context mode, it is divided into apply, call, and bind

call

The call method can call a function and specify that the function points to this

const RichWumon = {
    name: "Women".say: function () {
        console.log(this.name, "I want to pay for my son."); }}const obj = {
    name: "The dream silk"
}

RichWumon.say();			/ / women
RichWumon.say.call(obj);	/ / prick silk
Copy the code

Call the application

  1. Convert a pseudo-array to an array
let divs = document.querySelectorAll('div'); / / false array
// let divs = document.body.children;
console.log(divs);

function change(nodelist) {
    console.log(Object.prototype.toString.call(nodelist));
    return Array.prototype.slice.call(nodelist);

}
Copy the code

apply

The apply() method accepts an array of arguments. The call() method accepts a list of several arguments

You can modify the call code using Apply

const RichWumon = {
    name: "Women".say: function () {
        console.log(this.name, "I want to pay for my son."); }}const obj = {
    name: "The dream silk"
}

RichWumon.say();			/ / women
RichWumon.say.apply(obj);	/ / prick silk
Copy the code

The apply application

1. Simplify the log method

// Simplify the log method
function log() {
    // There is no need to change this
    console.log.apply(console.arguments);
}
Copy the code

The bind method

The **bind()** method creates a new function that can be bound to this of the new function

var name = 'Joe';
function Fn(){
    this.age = 1;
    
    console.log(this.name + this.age);
}

Fn();			/ / zhang SAN 1

// Return value: new function
// Argument: This pointer to the new function. When this pointer is bound to the new function, this does not change regardless of the call mode used.
let obj = {
    name:'jack',}const newFn = Fn.bind(obj);
newFn();		/ / jack Bauer 1
Copy the code

This point

  • Used alone, this refers to the global object

    console.log(this); 
    Copy the code
  • Function this refers to the global object

    function show(){
        console.log(this); 
    }
    
    show();
    Copy the code
  • Inside a function, the reference to this is undefined at function definition, only when the function is executed

    const a = 18;
    const obj = {
        a: 19.b: {
            a: 20.c: function () {
                console.log(this.a); 	/ / 20
            }
        }
    }
    obj.b.c();
    Copy the code
  • In a method, this refers to the object on which the method is called

    const obj ={
    	name:"White".say:function(){
    		console.log(this);		
    	}
    }
    obj.say()
    Copy the code

9. Arrow function

Formatting – Defines the syntax

// Arrow functions are anonymous functions, usually passed as arguments
// let test = function (a,b){
// let sum = a + b
// return sum
// }
// let test = (parameter) => {function body}
// A few small details
// 1. If the body of a function has only one sentence, you can omit {} and return the result of the body by default
// 2. If there is only one argument, then you can omit ()
// 3. If there is no argument, () cannot be omitted
// let test = (a,b) => a + b
let test = a= >  a + 10 

let res = test(100)
console.log(res)
Copy the code

features

// Arrow function this is certain, and will never change
// This in the arrow function refers to the context of the object in which the arrow function was created
let obj = {
    name: 'jack'.say: function () {
        return () = > {
            console.log(this) // obj}}}let fn = obj.say()
fn() // obj

let newobj = {}
newobj.fun = fn
newobj.fun() // obj

let rose = {
    name: 'rose'
}

fn.call(rose) // obj
Copy the code