javascript prototype function call and apply

Every function created in javascript have inherited prototype functions call and apply.They both execute the function with first argument being null or an instance of the function object, and the following arguments being the function arguments. The difference between them is that call method accepts an argument list, while apply method accepts a single array of arguments.

var fruits = ['Apple', 'Banana', 'Cherry', 'Orange', 'Pear'];

function print() {
	console.log(arguments);
}

print.call(null, fruits);
// { '0': [ 'Apple', 'Banana', 'Cherry', 'Orange', 'Pear' ] }

print.apply(null, fruits);
//{ '0': 'Apple',
//  '1': 'Banana',
//  '2': 'Cherry',
//  '3': 'Orange',
//  '4': 'Pear' }

Both of the following call and apply the slice method on the array object fruits get you the result of [ ‘Cherry’, ‘Orange’ ]. The result is the same, the difference is that when you use call, the arguments has to be passed individually, while the apply method accepts an array of arguments.

var fruits = ['Apple', 'Banana', 'Cherry', 'Orange', 'Pear'];
console.log(Array.prototype.slice.call(fruits, 2, 4));
console.log(Array.prototype.slice.apply(fruits, [2, 4]));
//[ 'Cherry', 'Orange' ]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search