1

I usually see that we should use an array in apply method and array of arguments in call method:

If I do the following (call method would return undefined):

var namelist = {
   f:'first name',
   l:'last name'
}
function func(a,b){
   console.log(this[a]+' '+this[b])
}

func.call(namelist,['f','l'])
//undefined undefined

func.apply(namelist,['f','l'])
//first name last name

But, look here both call and apply method works:

String.prototype.toUpperCase.call(['a','b','c']) //returns 'A,B,C'
String.prototype.toUpperCase.apply(['a','b','c']) //returns 'A,B,C'

Why the call method is working?

If I do use like this:

String.prototype.toUpperCase.call('a','b','c')
//this would return 'A' only.
Phil
  • 128,310
  • 20
  • 201
  • 202
Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187
  • Can't answer now because the question is closed but I'd say that your array is being converted to a string in both cases to be used as the `this` argument and `['a','b','c'].toString() === 'a,b,c'` – Phil Aug 06 '14 at 03:50

1 Answers1

0

The first argument to call and apply is the context for the function, the value of this.

But, look here both call and apply method works:

String.prototype.toUpperCase.call(['a','b','c']) //returns 'A,B,C'
String.prototype.toUpperCase.apply(['a','b','c']) //returns 'A,B,C'

Yes, that's not at all the same as your example. You're only passing one argument into each of call and apply, so they are identical. You're passing the same this with both methods. They're identical invocations.

String.prototype.toUpperCase.call('a','b','c')

//this would return 'A' only.

Yes, because you're passing only 'a' as this to toUpperCase. It would do the same thing (if it weren't an error) with apply('a', 'b', 'c'), again, because you're passing only 'a' as this to toUpperCase. The difference is that apply raises an error if you try to give it more than two arguments.


Original answer:

That isn't how you pass arguments with call.

Use func.call(namelist, 'f', 'l').

apply takes an array of arguments. call just takes the arguments.

Community
  • 1
  • 1
meager
  • 209,754
  • 38
  • 307
  • 315
  • 1
    I think OP's actual question is why do both `call` and `apply` produce the same result in `String.prototype.toUpperCase` – Phil Aug 06 '14 at 03:46
  • yeah, that's how call method supposed to be work but I am giving the example of String.prototype.toUpperCase.call(['a','b','c']) and why this is working... – Bhojendra Rauniyar Aug 06 '14 at 03:46
  • 1
    They do the same thing because because the **are** the same thing. They're identical invocations. You're passing your array as `this` to both methods. There is no difference between `apply(x)` and `call(x)`, they're identical. The difference is only in how they accept arguments. `apply(x, [y])` and `call(x, y)` are identical. – meager Aug 06 '14 at 03:47