Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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. :)