Difference between call apply and bind in javascript

Views

Difference between call, apply and bind in javascript

Both call and apply perform the same functions only difference between call and apply is that call execute a function in the context, or scope of the first argument that we pass to it and their related arguments.

In call we pass all the arguments with the object as a first argument.

Example as for call with object and single argument

 	var obj = { 		
		num : 10 	
	}; 	

	var addMore = function(a){ 		
		return this.num + a; 	
	}; 	

	console.log(addMore.call(obj,5)); // 15 

Call with object and multiple arguments

 	var obj = { 		
		num : 10 	
	}; 	

	var addMore = function(a,b,c){ 		
		return this.num + a + b + c; 	
	} 	

	console.log(addMore.call(obj,5,10,15)); // 40 

In apply we pass first argument as a object context and second argument as an array of arguments

 	var obj = { 		
		num : 10 	
	}; 	

	var addMore = function(a,b,c){ 		
		return this.num + a + b + c; 	
	} 	
	
	var arr = [5,10,15]; 	console.log(addMore.apply(obj,arr)); // 40 

In bind we pass object as an argument with the function and bind return us a function for later execute

 	var obj = { 		
		num : 10 	
	}; 	

	var addMore = function(a,b,c){ 		
		return this.num + a + b + c; 	
	} 	

	var bound = addMore.bind(obj); 	
	console.log(bound(5,10,15)); // 40 

Call and apply are pretty interchangeable. Just decide whether it’s easier to send in an array or a comma separated list of arguments.

Bind is a bit different. It returns a new function. Call and Apply execute the current function immediately.

How To Use Server-Sent Events …

How To Use Server-Sent Events in Node.js to Build a Realtime App. Server-Sent Events (SSE) is a technology based on HTTP. On the client-side, it provides an API called EventSource (part of the HTML5 standard) that allows us to connect to the server a …

read more
Views

How To Use node-cron to Run Sc …

How To Use node-cron to Run Scheduled Jobs in Node.js . cron provides a way to repeat a task at a specific time interval. There may be repetitive tasks such as logging and performing backups that need to occur on a daily or weekly basis.One method fo …

read more
Views