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

Use the more, less, and cat commands in Linux to view file contents

In Linux, the commands cat, more, and less can al...

MySQL transaction concepts and usage in-depth explanation

Table of contents The concept of affairs The stat...

50 Super Handy Tools for Web Designers

Being a web designer is not easy. Not only do you...

Tutorial on building nextcloud personal network disk with Docker

Table of contents 1. Introduction 2. Deployment E...

Installation tutorial of MySQL 5.7 green version under windows2008 64-bit system

Preface This article introduces the installation ...

A complete record of a Mysql deadlock troubleshooting process

Preface The database deadlocks I encountered befo...

What are Web Slices?

IE8 new feature Web Slices (Web Slices) Microsoft...

Graphic tutorial on installing Ubuntu 18.04 on VMware 15 virtual machine

In the past few years, I have been moving back an...

Vue implements student management function

This article example shares the specific code of ...

The difference between JS pre-parsing and variable promotion in web interview

Table of contents What is pre-analysis? The diffe...

How to use nginx as a proxy cache

The purpose of using cache is to reduce the press...

How to implement responsiveness in Vue source code learning

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

Solution to forgetting the MYSQL database password under MAC

Quick solution for forgetting MYSQL database pass...