-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??

Cloudboy22
  • 1,496
  • 5
  • 21
  • 39

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
  • 142,382
  • 31
  • 172
  • 209
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • what does If a function is defined to accept an arbitrary number of arguments, mean? i mean arbritary?? – Cloudboy22 Oct 20 '15 at 06:47
  • @MarcAndreJiacarrini Do we really need to tell you [how to look up words in a dictionary](https://en.wiktionary.org/wiki/arbitrary)? – poke Oct 20 '15 at 06:53
  • @poke the dictionary contains many meanings dude... which one will fit here... Mr. Cool guy?? – Cloudboy22 Oct 20 '15 at 06:56
  • 2
    @MarcAndreJiacarrini—"*an arbitrary number*" means any number, though functions can accept from 0 to ??? arguments. – RobG Oct 20 '15 at 06:56
  • @RobG Thank you for improving answer :) – Tushar Oct 20 '15 at 07:03
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
  • 18,121
  • 8
  • 60
  • 81