33 concepts JavaScript developers should understand 6-this, call, apply and bind

33 concepts JavaScript developers should understand 6-this, call, apply and bind

Directory

  1. call stack
  2. primitive type
  3. Value types and reference types
  4. Implicit, explicit, nominal and duck typing
  5. == and ===, typeof and instanceof
  6. this, call, apply and bind
  7. Function scope, block scope and lexical scope
  8. Closure
  9. Higher order functions such as map, reduce, filter etc.
  10. expressions and statements
  11. variable promotion
  12. Promise async and wait
  13. Immediate function execution, modularity, namespace
  14. recursion
  15. algorithm
  16. data structure
  17. Message queue and event loop
  18. setTimeout, setInterval and requestAnimationFrame
  19. Inheritance, polymorphism and code reuse
  20. Bitwise operators, array-like objects and typed arrays
  21. DOM tree and rendering process
  22. new and constructor, instanceof and instance
  23. Prototype inheritance and prototype chain
  24. Object.create and Object.assign
  25. Factory functions and classes
  26. Design Patterns
  27. Memoization
  28. Pure functions, function side effects and state changes
  29. Performance-consuming operations and time complexity
  30. JavaScript engine
  31. Binary, decimal, hexadecimal, scientific notation
  32. Partial functions, currying, Compose and Pipe
  33. Code cleanliness

Introduction

Record a process of relearning JavaScript. The article is not written in order. The directory link will be updated after it is written. The directory of this article was created with reference to @leonardomso. The English version project address is here

this in 1.js

In object-oriented languages, this represents a reference to the current object.

But in JavaScript this is not fixed, it changes as the execution environment changes.

  • In a method, this represents the object to which the method belongs.
  • If used alone, this represents the global object.
  • In a function, this represents the global object.
  • In a function, in strict mode, this is undefined.
  • In an event, this represents the element receiving the event.

This is mainly used in:

  • this in the constructor;
  • this in ordinary functions;
  • this in object functions;
  • call, apply, bind change this
  • this in arrow function

1.1 this in the constructor

When called as a constructor, this is the newly created object

function Person(name) {<!-- -->
    this.name = name;
}
const p = new Person('Zhang San');
console.log(p.name);

1.2 this in ordinary functions

This in a normal function is window, “use strict”; in strict mode it is undefined

"use strict";
function getVal() {<!-- -->
    console.log(this); //window, undefined in strict mode
}
getVal();

1.3 this in object function

When called as a method, this is the object on which the method is called

var person = {<!-- -->
    firstName: "张",
    lastName : "三",
    fullName : function() {<!-- -->
        return this.firstName + " " + this.lastName;
    }
};
console.log(person.fullName());//Zhang San

1.4 Use this alone

Used alone, this points to the global object.

In the browser, window is the global object [object Window]:

In strict mode, if used alone, this also points to the global object.

"use strict";
var x = this;
console.log(x);//window

1.5 this in the event

In an event, this represents the element that receives the event

<button onclick="this.style.display='none'">Click me and I will disappear</button>

1.6 this in arrow functions

Several explanations of arrow function this
1. When we use the arrow function, the arrow function will help us bind the value of the outer this by default, so the value of this in the arrow function is the same as the outer this.

2. This in the arrow function refers to this in the nearest scope.

3. Search this layer by layer in the outer scope until there is a definition of this

4. Some arrow functions do not have their own this. Not suitable for defining methods of an object.

The arrow function does not have its own this pointer. It will capture the outer execution environment in which it is defined and inherit this this value. The this point of the arrow function is determined when it is defined and will never change afterwards. (! Forever)

const obj = {<!-- -->
    fun1: function () {<!-- -->
        console.log(this);
        return () => {<!-- -->
            console.log(this);
        }
    },
    fun2: function () {<!-- -->
        return function () {<!-- -->
            console.log(this);
            return () => {<!-- -->
                console.log(this);
            }
        }
    },
    fun3: () => {<!-- -->
        console.log(this);
    }
}
let f1 = obj.fun1(); // obj
f1() //obj
let f2 = obj.fun2();
let f2_2 = f2(); // window
f2_2() // window
obj.fun3(); // window

2 .apply

It has two functions, which are related to its ginseng.

  1. Change what this points to.
  2. The second parameter of apply accepts an array
var person = {<!-- -->
    fullName: function() {<!-- -->
        return this.firstName + " " + this.lastName;
    }
}
var person1 = {<!-- -->
    firstName: "张",
    lastName: "三",
}
person.fullName.apply(person1); // Will return "Zhang San"
console.log(person.fullName.apply(person1));

When apply is called, who is the function that calls apply? (person.fullName), share this function with person1 and let person1 call it

3.call

var person = {
    fullName: function(city, country) {
        return this.firstName + " " + this.lastName + "," + city + "," + country;
    }
}
var person1 = {
    firstName:"Zhang",
    lastName: "三"
}
person.fullName.call(person1, "Beijing", "China");
console.log(person.fullName.call(person1, "Beijing", "China"));//Zhang San, Beijing, China

In fact, apply and call are basically similar. The only difference between them is the parameters passed in. The difference between apply and call is that the call method accepts several parameter lists, while apply receives an array containing multiple parameters.

4.bind

The bind() method is mainly to bind a function to an object. bind() will create a function, and the value of this object in the function body will be bound to the value of the first parameter passed into bind().

const person = {<!-- -->
        name: 'Zhang San',
        sayHello: function(city) {<!-- -->
            console.log(`My name is ${<!-- -->this.name} and my home is ${<!-- -->city}`);
        }
    };
    const person2 = {<!-- -->
        name: '李思'
    };
    const sayHelloFn = person.sayHello.bind(person2,"Beijing");
    sayHelloFn(); // My name is Li Si. I live in Beijing.

In the above code, we define a person object and a person2 object, both of which contain a name property. We use the bind method to bind the sayHello method of the person object to the person2 object and create a new function sayHelloFn. When we call sayHelloFn, its this value points to the person2 object, so the output becomes “My name is Li Si. My home is in Beijing.”

In addition to specifying a this value, the bind method can also be used to curry functions. Currying is a technique for converting a function that accepts multiple arguments into a function that accepts one argument. For example:

function add(a, b) {<!-- -->

    return a + b;

}

const add5 = add.bind(null, 5);
console.log(add5(3)); // Output: 8

In the above code, we define an add function that takes two parameters and returns their sum. We use the bind method to curry the add function into a new function add5 that takes one argument and adds it to 5. Therefore, when we call add5(3), the return value is 8.