this in the callback function (normal function and arrow function) of javascript

The value of the this object in the function is determined when the function is called and executed. An execution context is created at this point.

For arrow functions, it does not have its own this and cannot be used as a constructor. The this object in the arrow function is the object where it was defined,

Not the object on which it was called.

For the this object in the callback function. Below are two small examples.

1. For the setTimeout function

Ordinary function: When executed after 100ms, this points to the window object.

function foo() {
	setTimeout(function() {
		console.log(this);
		console.log("id: ",this.id);
		}, 100);
	}
	var id = 21;

	foo(); //this points to the window object, 21     

	foo.call({id:42}); //this points to the window object, 21

Arrow function: 

function foo() {
	setTimeout(() =>{
		 console.log(this);
		 console.log("id: ",this.id);
	}, 100);
}
 var id = 21;
 foo(); //this points to window
 foo.call({id:42}); //this points to the {id:42} object
Arrow functions: this is valid when it is defined. this always points to the object where the function definition is valid.


2. For event handlers

Ordinary function:

var handler = {
		 	id:'123456',
		 	init:function () {
		 		document.addEventListener('click', function(e) {
		 			this.doSomething(e.type); //this points to the window object. So it will go wrong
		 		},false);
		 	},
		 	doSomething:function (type) {
		 		console.log("handler"+type+"for"+this.id);
		 	}
		 };

		 handler.init();
Arrow function:
         var handler = {
		 	id:'123456',
		 	init:function () {
		 		document.addEventListener('click', (e)=> {
		 			this.doSomething(e.type);                  //this指向handler
		 		},false);
		 	},
		 	doSomething:function (type) {
		 		console.log("handler"+type+"for"+this.id);
		 	}
		 };

		 handler.init();

3. Summary:

For the this object in the callback function. For ordinary functions, this points to the object where the call is made (ie the window object). For arrow functions, this points to the object where the definition takes effect.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325851197&siteId=291194637