Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Foundations Objects Call and Apply

lata sharma
seal-mask
.a{fill-rule:evenodd;}techdegree
lata sharma
iOS Development Techdegree Student 5,292 Points

using genericGreet function in context of andrew and passing array of args1

Set the 'greeting' variable, on line 29, by using the 'genericGreet' function in the context of 'andrew' with the array of arguments, 'args1'.

7 Answers

cpauciello
cpauciello
26,629 Points

You need to use the apply() method, as it will let you invoke the function with arguments as an array (or an array like-object). See here

Pseudo syntax:

  theFunction.apply(valueForThis, arrayOfArgs);

Answer:

   var greeting = genericGreet.apply(andrew, args1);
cpauciello
cpauciello
26,629 Points

Ah ok, use .apply(andrew, args1) on the first genericGreet, and remove that last line.

So instead of:

  var greeting = genericGreet;
  genericGreet.apply(andrew, args1);

It should just be:

var greeting = genericGreet.apply(andrew, args1);
lata sharma
seal-mask
.a{fill-rule:evenodd;}techdegree
lata sharma
iOS Development Techdegree Student 5,292 Points

Chris,

I tried that already and this is the error msg I get: Bummer! The 'greeting' variable should be 'Hello Michael, my name is Andrew and I am in a awesome mood!'.

cpauciello
cpauciello
26,629 Points

Well that's weird, passes for me every time. can you post your code?

      var genericGreet = function(name, mood) {
        name = name || "you";
        mood = mood || "good";
        return "Hello " + name + ", my name is " + this.name +
          " and I am in a " + mood + " mood!";
      }

      var andrew = {
        name: "Andrew"
      }

      var args1 = ["Michael", "awesome", ":)"];

      var greeting = genericGreet.apply(andrew, args1); 
lata sharma
seal-mask
.a{fill-rule:evenodd;}techdegree
lata sharma
iOS Development Techdegree Student 5,292 Points

Here it is:

var genericGreet = function(name, mood) { name = name || "you"; mood = mood || "good"; return "Hello " + name + ", my name is " + this.name + " and I am in a " + mood + " mood!"; }

  var andrew = {
    name: "Andrew"
  }

  var args1 = ["Michael", "awesome", ":)"];

  var greeting = genericGreet;
  genericGreet.apply(andrew, args1);
cpauciello
cpauciello
26,629 Points

You're welcome. :)