33 concepts JavaScript developers should understand 6-this, call, apply and bind
Directory
- call stack
- primitive type
- Value types and reference types
- Implicit, explicit, nominal and duck typing
- == and ===, typeof and instanceof
- this, call, apply and bind
- Function scope, block scope and lexical scope
- Closure
- Higher order functions such as map, reduce, filter etc.
- expressions and statements
- variable promotion
- Promise async and wait
- Immediate function execution, modularity, namespace
- recursion
- algorithm
- data structure
- Message queue and event loop
- setTimeout, setInterval and requestAnimationFrame
- Inheritance, polymorphism and code reuse
- Bitwise operators, array-like objects and typed arrays
- DOM tree and rendering process
- new and constructor, instanceof and instance
- Prototype inheritance and prototype chain
- Object.create and Object.assign
- Factory functions and classes
- Design Patterns
- Memoization
- Pure functions, function side effects and state changes
- Performance-consuming operations and time complexity
- JavaScript engine
- Binary, decimal, hexadecimal, scientific notation
- Partial functions, currying, Compose and Pipe
- 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.
- Change what this points to.
- 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.