Similarities and differences between this keyword and call, apply, bind in js

this is a keyword

The use of this is divided into two cases

①In the constructor, when using new to get a new object, this represents the new object

②When the function where this is running, this represents the caller. Among them, the caller of a function that runs directly like test() is windows, and there are some special examples such as call, apply, bind, etc.

 

Similarities and differences between call, apply, bind

All three are used to change the context, that is, the pointer to this object

Some articles on the Internet say that they have changed the scope chain, and they have written simple code to test No, just change this in the execution context

The functions of call and apply are the same, the difference lies in the way of accepting parameters. call is to pass parameters in order, apply is to pass parameters in an array, and bind is to return a new object determined by the context.

 

<script type="text/javascript">
		function x(A,B){
			alert(A+B+this.C);
		}
		var C = 4;
		x(1,1);//6
		
		var D = {C:5};
		var y = x.bind (D);
		y(1,1);//7
		
		var E = {C:6};
		x.call(E,1,1);//8
		x.apply(E,[1,1]);//8
</script>

 

 

 

callback callback function

The definition of the callback function in js is: function A is passed as a parameter to another function B, and this function B executes function A. We use A as the callback function. call anonymous callback function if it has no name

<script type="text/javascript">
		function n(A,B,callback){
			var C = A+B;
			callback(C);
		}
		function x(A){
			alert(A);
		}
		n(1,2,x);//3
		n(1,2,function(A){alert(A+1);});//4
</script>

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327061207&siteId=291194637