-2

i am reading about call function in js. Now i have this code

var o = {
  name: 'i am object',
  age: 22
}

function saymyName(arguentToFunc) {
  console.log('my name is ' + this.name + 'and thw argument  passed is ' + arguentToFunc);
}

saymyName.apply(o, 'hello there');

But it gives an error message saying Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type

In the book the definite guide it is written that the second argument is the value passed to the function. eg here it is hello there So why the error?

Hey according to the book .apply needs this what does If a function is defined to accept an arbitrary number of arguments, mean? i mean arbritary??

Marc Andre Jiacarrini
  • 1,444
  • 3
  • 20
  • 36

2 Answers2

3

Use call instead of apply, as apply needs the second parameter to be an Array–like object.

Use apply when an array of values needs to be sent as parameters to the called function (e.g. to pass all the arguments of the currently executing function using the arguments object).

Demo

var o = {
  name: 'i am object',
  age: 22
};

function saymyName(arguentToFunc) {

  console.log('my name is ' + this.name + 'and thw argument  passed is ' + arguentToFunc);
}

saymyName.call(o, 'hello there');

Also, see bind for how to set a function's this to a fixed value, regardless of how it's called.

RobG
  • 134,457
  • 30
  • 163
  • 204
Tushar
  • 82,599
  • 19
  • 151
  • 169
3

apply requires an array of parameter, you should use it as

saymyName.apply(o, ['hello there']);

or else you could use call

saymyName.call(o, 'hello there');
Matteo Tassinari
  • 17,408
  • 7
  • 58
  • 80