Detailed explanation of this pointing problem in JavaScript function

Detailed explanation of this pointing problem in JavaScript function

this keyword

Which object calls the function, and which object does this in the function point to?

**Strict mode:** In the global environment, this refers to undefined

**Non-strict mode: **In the global environment, this refers to window

Globally defined functions are called directly, this => window

function fn(){
	console.log(this);
	// At this point this points to window
}
fn();
// Equivalent to window.fn()

Function call inside an object, this => caller

var obj = {
	fn:function(){
		console.log(this);
	}
}
obj.fn();
// At this time this points to obj

Timer processing function, this => window

setTimeout(function(){
	console.log(this);	
},0)
// At this time, this in the timer processing function points to window

Event handling function, this => event source

div.onclick = function(){
	console.log(this);
}
//When you click on div, this points to div

Self-invoking function, this => window

(function () {
  console.log(this)
})()
// At this point this points to window

Change this to point to

What we just talked about are the this pointers in the basic function calling methods. We also have three ways to ignore the this pointer of the function itself and point it to other places. These three methods are call / apply / bind, which are methods that forcibly change the pointer of this.

  • call/apply/bind is used after the function call, and the this pointer of the function itself can be ignored.
  • When call and apply are used, the function is automatically called immediately. When bind is used, a function is created, but it needs to be called manually.

call

Syntax: fn.call(where this points to in the fn function body, arg1, arg2, ...);

Function: Call the bound function fn, specify its this pointer and pass parameters

parameter:

  • The first parameter: this points to
  • The remaining parameters: the values ​​that need to be passed in, can be multiple, separated by commas

Use the call method without passing parameters

var num = 666;

function fn() {
  console.log('num = ', this.num);
}

fn.call(); // num = 666

Use the call method to specify this

var name = 'Rose';
var obj = {name:'Jack'};
function fn(){
	console.log(this.name);
}
fn(); // Rose
fn.call(); // Rose
fn.call(obj); // jack

Use the call method to specify this and pass parameters

var name = 'Rack';
var obj = {name:'Jack'};
function fn(a,b){
	console.log(this,a,b);
}
fn(1,2); // window 1 2
fn.call(obj,1,2); // obj 1 2
fn(1,3); // window 1 3

apply

The apply method accepts an array containing multiple parameters.

Syntax: fn.apply(where this points to in the fn function body, [arg1, arg2, ...]);

Function: Call the bound function fn, specify its this pointer and pass parameters

parameter:

  • The first parameter: the object pointed to by this
  • The second parameter: an array containing multiple parameters
var obj = {name:'jack'};
function fn(a,b){
	console.log(this,a,b);
}
fn(1,2); // window 1 2
fn.apply(obj,[1,2]); // obj 1 2

Merging arrays using apply

Use push to append elements to an array. If the argument is an array, it will add the array as a single element instead of adding each element in the array, so we end up with an array within an array.

var arr1 = [1,2];
var arr2 = [3,4];
arr1.push(arr2);
console.log(arr1); // [1,2,[3,4]]	

Although concat can merge arrays, it does not add elements to an existing array, but creates and returns a new array.

var arr1 = [1,2];
var arr2 = [3,4];

var arr3 = arr1.concat(arr2);
console.log(arr1); // [1,2]
console.log(arr3); // [1,2,3,4]

What if we want to append elements to an existing array? cycle? No! This is where apply comes in handy

var arr1 = [1,2];
var arr2 = [3,4];

arr1.push.apply(arr1,arr2);
console.log(arr1); // [1,2,3,4]

Using apply with built-in functions

/* Find the largest/smallest number in the array*/
var numbers = [5, 6, 2, 3, 7];

var max = Math.max(numbers)
var min = Math.min(numbers)
console.log(min,max); // NaN NaN

var max = Math.max.apply(null, numbers); 
/* Basically equivalent to Math.max(numbers[0], ...) or Math.max(5, 6, ..) */
var min = Math.min.apply(null, numbers);
console.log(min,max); // 2 7

bind

Syntax: fn.bind(the pointer of this in the fn function body, arg1, arg2, ...);

Function: Create a new bound function, specify its this pointer and pass parameters, it must be called before it will be executed

parameter:

  • The first parameter: the object pointed to by this
  • The remaining parameters: the values ​​that need to be passed in, can be multiple, separated by commas
var obj = {name:'jack'};
function fn(a,b){
	console.log(this,a,b);
}
fn(1,2); // window 1 2
fn.bind(obj,1,2); // Not called and not executed fn.bind(obj,1,3)() // obj 1 3
var newFn = fn.bind(obj,3,4);
newFn(); // obj 1 4
newFn(5,6); // obj 3 4

Summarize

This is the end of this article about the this pointing problem in JavaScript functions. For more relevant JavaScript function this pointing content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of this pointing in JS arrow function
  • Detailed explanation of function classification and examples of this pointing in Javascript
  • Detailed analysis of the this pointing problem inside JS anonymous function
  • In-depth understanding of the scope of js functions and this pointing
  • JavaScript makes this in the function parameter in setInteval point to a specific object
  • Detailed explanation of JavaScript function this pointing problem

<<:  Detailed tutorial on installing Protobuf 3 on Ubuntu

>>:  Detailed explanation of the configuration method of MySQL master-slave replication read-write separation

Recommend

In-depth understanding of Vue transition and animation

1. When inserting, updating, or removing DOM elem...

Introduction to the B-Tree Insertion Process

In the previous article https://www.jb51.net/arti...

How to add a disk in Vmware: Expand the disk

This article describes how to add or expand a dis...

Native Js implementation of calendar widget

This article example shares the specific code of ...

Several popular website navigation directions in the future

<br />This is not only an era of information...

Complete steps for mounting a new data disk in CentOS7

Preface I just bought a new VPS. The data disk of...

Analysis and description of network configuration files under Ubuntu system

I encountered a strange network problem today. I ...

Advantages and Problems of XHTML CSS Website Design

XHTML is the standard website design language cur...

Linux Domain Name Service DNS Configuration Method

What is DNS The full name of DNS is Domain Name S...

Docker Tutorial: Using Containers (Simple Example)

If you’re new to Docker, take a look at some of t...

What is the file mysql-bin.000001 in mysql? Can it be deleted?

After installing MySQL using ports, I found that ...

Comprehensive understanding of line-height and vertical-align

Previous words Line-height, font-size, and vertica...

How to create, start, and stop a Docker container

1. A container is an independently running applic...

Provides helpful suggestions for improving website design

<br />Scientifically Design Your Website: 23...

How to implement responsiveness in Vue source code learning

Table of contents Preface 1. Key Elements of a Re...