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

uniapp dynamic modification of element node style detailed explanation

Table of contents 1. Modify by binding the style ...

CSS realizes process navigation effect (three methods)

CSS realizes the process navigation effect. The s...

Self-study of MySql built-in functions knowledge points summary

String functions Check the ascii code value of th...

HTML code to add icons to transparent input box

I was recently writing a lawyer recommendation we...

How to increase HTML page loading speed

(1) Reduce HTTP requests. (Merge resource files a...

Vue implements a search box with a magnifying glass

This article shares with you how to use Vue to im...

Docker image management common operation code examples

Mirroring is also one of the core components of D...

JavaScript explains the encapsulation and use of slow-motion animation

Implementing process analysis (1) How to call rep...

Implementation steps for installing FTP server in Ubuntu 14.04

Table of contents Install Software Management Ano...

How to hide and remove scroll bars in HTML

1. HTML tags with attributes XML/HTML CodeCopy co...

How to make JavaScript sleep or wait

Table of contents Overview Checking setTimeout() ...

Detailed explanation of HTML page header code example

Knowledge point 1: Set the base URL of the web pa...

How to process local images dynamically loaded in Vue

Find the problem Today I encountered a problem of...

Mybatis paging plug-in pageHelper detailed explanation and simple example

Mybatis paging plug-in pageHelper detailed explan...