Home » Underscore » Underscore Functions

Underscore Functions

Welcome to the third module of Undersore.js tutorial. In this Module we will cover some basic concepts of underscore functions, how underscore library can bind the function, how can we add delay in function execution and finally how can we wrap the function inside another function.

So let’s go through each function one by one.

 

_.bind(function, object, [*arguments])
_.bind() function helps to manage the reference of this pointer inside function.

var addPersonDetails = function(value){
       return "My name is "+this.name+
	         ", i am "+this.age+" years old."+
		 "I am from "+value.country+"."+
		 " I play "+value.sport
		};

var bindPersonData = _.bind(addPersonDetails, 
		objectArray[0], 
		{country:"India", sport:"football"});
console.log(bindPersonData());

//console: My name is Himanshu, i am 26 years old.I am from India. I play football

In above example i have an object (objectArray[0]) and a method (addPersonDetails). Method is not defined inside an object, but still i am referencing object properties (name, age) inside “addPersonDetails” method. This all is possible by the use of _.bind() function, here i am binding object and method, which means, i have a “addPersonDetails” method and i am passing objectArray[0] as a context for that method.
Additionally you can pass parameters also to _.bind() function. So I am passing country and sport as a parameter.

 

_.bindAll(object, *methodNames)
_.bindAll() function is same as _.bind() function, the only difference is _.bindAll() function creates binding for all the functions.
The main advantage of _.bindAll() function is we do not need to return any value as we have to do in _.bind() function.

var person = function(firstName,lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.fullName = function(){
   console.log(this.firstName + " "+this.lastName);
  }
}
var personOne = new person('Himanshu','Chahar');
_.bindAll(personOne, 'fullName');
var personName = personOne.fullName;
personName();

// console: Himanshu Chahar

To understand _.bindAll() function in more detail let’s change the above code little bit.

var personOne = new person('Himanshu','Chahar');
personOne.fullName(); // removed the binding

// console: Himanshu Chahar // result is same

Now remove the binding and assign the function to variable as shown below

var personOne = new person('Himanshu','Chahar');
var personName = personOne.fullName;
personName();

// console: undefined undefined

Above code results “undefined undefined”, the reason is personName is referencing window’s object and window’s object doesn’t have any function called fullName.
To get more clarity on that, lets print this pointer in console.

var person = function(firstName,lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.fullName = function(){
   console.log(this); // print this
   console.log(this.firstName + " "+this.lastName);
  }
}
var personOne = new person('Himanshu','Chahar');
var personName = personOne.fullName;
personName();

// console: Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}
// console: undefined undefined

So it’s clear from the above code that we are getting window’s object in this pointer.
To make the above code work, you should bind personOne with fullName function and re run the code.

Result would be:

// console: person {firstName: "Himanshu", lastName: "Chahar", fullName: function}
// console: Himanshu Chahar

Now this pointer will refer to person’s object.

 

_.delay(function, wait, [*arguments])
_.delay() function is same as javascript’s setTimeOut function, it adds delay to function call.
We can pass time in milliseconds in wait parameter. We can pass additional arguments also.

var logFunction = function(value){
   console.log("call this after "+value+" seconds");
}
_.delay(logFunction,3000,"3");

// console: call this after 3 seconds

This function will be called after 3 seconds; additionally we are passing value also which will be used by logFunction.

 

_.defer(function, [*arguments])
_.defer() function is used to defer the execution of the function until the current call stack is cleared.
This function can be useful where we want to update the UI after completing some other task or calculation.

var deferFunction = function(){
   console.log("defer this function");
};

_.defer(deferFunction);
console.log("print this value"); // this function will be called first and then defer function gets called

// console: print this value
// defer this function

 

_.throttle(function, wait, [options])
_.throttle() function calls the given function only once in given interval of time.
For example, if you have a button and you want to send only one value in 1000ms then throttle is what you need. Throttle will perform an action only once in every 1000ms no matter how many times user clicks the button.

To understand this add button to your html.

html:

<button id="id_callThrottle" onclick="callthrottle()">Throttle</button>

JS:

var throttleFunction = function(){console.log("throttle function");};
var callthrottle = _.throttle(throttleFunction,5000);

// console: throttle function

callthrottle” function will be called only once in every 5000ms, no matter how many times you click “Throttle” button.

 

_.debounce(function, wait, [immediate])
_.debounce() function can be used to make sure that the function is fired after given interval of time.

html:

<button id="id_callDebounce" onclick="callDebounce()">Debounce</button>

JS:

var debounceFunction = function(){console.log("debounce function");};
var callDebounce = _.debounce(debounceFunction,3000);

// console: debounce function

This will be called after 3 seconds, after user clicks on “Debounce” button.

 

_.once(function)
function wrapped around _.once() function will be called only once, repeated calls will have no effect on this function.

_(3).times(_.once(function(){console.log("function call");}));

// console: function call

In above function we are calling _.times() function which calls the function 3 times, we are passing _.once() function to _.times() function. So instead of 3 times this function will be called only once.

 

_.after(count, function)
_.after() function is gets called after particular number of times the function has been executed.
_.after() function can be found useful in asynchronous calls.

html:

<button id="id_callafter" onclick="callAfter()">After</button>

JS:

var callAfter = _.after(5,function(){
   console.log("now call this function");
});

Function that we are passing to _.after() will start executing only after clicking “After” button 5 times.

 

_.wrap(function, wrapper)
_.wrap() function allows us to wrap function inside the wrapper function.
This can be little bit confusing without an example, so lets take a look at the example.

var function1 = function(name){ // function which we want to wrap
   return name;
}

var wrapperFunction = function(functionToWrap){ // wrapper function
   return "My name is: "+functionToWrap("Himanshu");
}

var wrappedFunction = _.wrap(function1,wrapperFunction);

console.log(wrappedFunction());

// console: My name is: Himanshu

In above example we are using value returned by function1 in wrapperFunction, to do that we are wrapping function1 inside the wrapperFunction.

We can wrap Object also:

var personDetails = {
   name:'Himanshu',
   age:'26',
   gender:'male'
}

var detailWrapperFunction = function(e){
   return "Name: "+e.name+" Age: "+e.age+" Gender: "+e.gender;
}

var detailWrappedFunction = _.wrap(personDetails,detailWrapperFunction);
console.log(detailWrappedFunction());

// console: Name: Himanshu Age: 26 Gender: male

Here we are wrapping personDetails object inside detailWrapperFunction.

 

_.compose(*functions)
_.compose() function takes list of functions and each function consumes the result of the function it follows.
In mathematical terms, composing the functions f(), g(), and h() produces f(g(h()))
for example if you write _.compose(function1,function2,function3); then “function3” will be called first and its result will be given to “function2″ and so on.

var function1 = function(value){
   console.log("function 1 completed");
   console.log(value*value); // 12.5*12.5 = 156.25
}

var function2 = function(value){
   console.log("function 2 completed");
   return value/2; // 25/2 = 12.5
}

var function3 = function(value1,value2){
   console.log("function 3 completed");
   return value1+value2; // 12+13 = 25
}

var composedFunction = _.compose(function1,function2,function3);
composedFunction(12,13);

// console: 156.25

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>