-1

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

2
  • Hey why am i downvoted? Commented Oct 20, 2015 at 6:43
  • @Yeah but i was confused!! Commented Oct 20, 2015 at 6:45

2 Answers 2

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');
Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

what does If a function is defined to accept an arbitrary number of arguments, mean? i mean arbritary??
@MarcAndreJiacarrini Do we really need to tell you how to look up words in a dictionary?
@poke the dictionary contains many meanings dude... which one will fit here... Mr. Cool guy??
@MarcAndreJiacarrini—"an arbitrary number" means any number, though functions can accept from 0 to ??? arguments.
@RobG Thank you for improving answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.