Monday, 4 April 2016

Indirectly calling functions using the call() and apply() function in javascript

//Using call() and apply() functions
var updateZipCode = function(){
 console.log(this);//Window(....) //this points to the global object Window
};
updateZipCode();
//************************************************************************
var updateZipCode = function(){
 console.log(this);//Object{}
};
/* In the line given below we are passing an empty object as parameter to the call mehtod so that inside the function updateZipCode 'this' can refer to it. */
updateZipCode.call({});
//************************************************************************
var updateZipCode = function(){
 console.log(this);//Object {zip: "22675"}
};
/* In the line given below we are passing an object that has a property zip along with the valu of that property set to 22675 as parameter to the call mehtod so that inside the function updateZipCode 'this' can refer to it. */
updateZipCode.call({zip: '22675'});
//************************************************************************
//We can pass a variable as argument to call() as shown below
var updateZipCode = function(){
 console.log(this);//Object {zip: "24358"}
};
//Making a variable to be passed to the method call() as argument.
var zipCode = {
 zip : '24358'
};
updateZipCode.call(zipCode);
//************************************************************************
//Using a function that requires arguments. 
var updateZipCode = function (newZip, country) {
 console.log(newZip + ' ' + country);//98679 japan
};
var zipCode = {
 zip: '45345'
};
/*In the line below we are passing the object zipCode as the first argument which will be associated with the keyword 'this' in the function updateZipCode(). We are also passing the arguments for the neqZip and country.
*/
updateZipCode.call(zipCode, '98679', 'japan');
//************************************************************************
/* The apply() function gets an array as argument and break down this array 
in to arguments to pass them to the function updateZipCode(). If we supply 
a list of arguments instead of an array it will not work. */
var updateZipCode = function(newZip, country){
 console.log(newZip + ' ' + country);//29468 japan
};
var zipCode = {
 zip: '34679'
};
updateZipCode.apply(zipCode, ['29468', 'japan']);
/*
If we use apply() but instead of an array, pass it a list then we get the 
following error:
Uncaught TypeError: CreateListFromArrayLike called on non-object
*/
//updateZipCode.apply(zipCode, '29468', 'japan');
//************************************************************************

3 comments: