Reputation: 95
While Passing Array in call Method works well as I am able to iterate it,but
in case of apply it gives an error while iterating the array. (although it only takes array-like object as argument)
var student = {
fname:'vipul',
lname:'jadhav',
fullName:function(){
return (this.fname+' '+this.lname);
}
}
function getMarks(marks){
console.log('USER : '+this.fullName());
console.log('MARKS :')
for(let i of marks){
console.log('marks :'+i);
}
}
var getMarksCall = getMarks.call(student,[99,78,89,90]);
var getMarksApply = getMarks.apply(student,[99,78,89,90]);
It gives an error as
Uncaught TypeError: marks is not iterable
In another case when i changes for loop to
for(let i=0 ;i<marks.length;i++){
console.log('marks :'+marks[i]);
}
then i got to know that marks is only the first value of array.(see image) debugger_screenshot
1.what is the actual difference between the call and apply.. because call also supports the array as argument then what is the need of apply?
2.why the difference between iterating the array in two methods? 3.How to iterate the array in apply?
Could anyone please help me to geeting this ?
Upvotes: 1
Views: 49
Reputation: 1
apply() method accepts an array of arguments. So if you are passing an array as an argument then it should be inside an array.
var getMarksApply = getMarks.apply(student, [[99, 78, 89, 90]]);
The only difference between both is call() method can accept a parameter or array of parameters but apply() method only accepts an array of parameters. No such difference between iterating an array in both of the methods. For more details please refer this https://www.codingame.com/playgrounds/9799/learn-solve-call-apply-and-bind-methods-in-javascript
Upvotes: 0
Reputation: 386560
Function#apply
needs an array of parameters, but here you have an array of values which is not iterable for the inner for
loop.
To get it working, you need to wrap the array as parameter in an array.
var student = {
fname: 'vipul',
lname: 'jadhav',
fullName: function() {
return (this.fname + ' ' + this.lname);
}
}
function getMarks(marks) {
console.log('USER : ' + this.fullName());
console.log('MARKS :')
for (let i of marks) {
console.log('marks :' + i);
}
}
var getMarksCall = getMarks.call(student, [99, 78, 89, 90]);
var getMarksApply = getMarks.apply(student, [[99, 78, 89, 90]]);
// ^ ^
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1