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

mysql implements the operation of setting multiple primary keys

User table, ID number must be unique, mobile phon...

How to quickly log in to MySQL database without password under Shell

background When we want to log in to the MySQL da...

IE8 compatibility notes I encountered

1. IE8's getElementById only supports id, not ...

How to monitor mysql using zabbix

Zabbix deployment documentation After zabbix is ​...

Detailed explanation of creating, calling and managing MySQL stored procedures

Table of contents Introduction to stored procedur...

14 techniques for high-performance websites

Original : http://developer.yahoo.com/performance...

Tutorial on how to quickly deploy clickhouse using docker-compose

ClickHouse is an open source column-oriented DBMS...

CentOS uses expect to remotely execute scripts and commands in batches

Sometimes we may need to operate servers in batch...

Example of building a redis-sentinel cluster based on docker

1. Overview Redis Cluster enables high availabili...

Summary of the use of CSS scope (style splitting)

1. Use of CSS scope (style division) In Vue, make...

A brief talk about Rx responsive programming

Table of contents 1. Observable 2. Higher-order f...

Explanation of the problem that JavaScript strict mode does not support octal

Regarding the issue that JavaScript strict mode d...

Linux process management tool supervisor installation and configuration tutorial

Environment: CentOS 7 Official documentation: htt...