0
var clientData = {
    id: 1969,
    fullName: "Not Set",
    setUserName: function (firstName, lastName)  {
      clientData.fullName = firstName + " " + lastName;
      console.log(clientData.fullName);
    }
};

function getUserInput(firstName, lastName, callback)  {  
  //why can't I say clientData.callback (firstName, lastName); instead
  callback (firstName, lastName);
}

getUserInput ("Peter", "Pan", clientData.setUserName);

As is commented in the code, why can't I say clientData.callback (firstName, lastName); if what the callback argument is referencing is the function that should be accessible from clientData with dot access? If clientData.setUserName is just a reference to a function object, I shouldn't be accidentally saying clientData.clientData.setUsername with my commented code, right?

I'm a beginner, and because it's not working I'm sure I'm thinking of something wrong.

1
  • You can say clientData.setUserName(), you cannot say clientData.callback() - there is no such method. Commented Apr 14, 2015 at 4:19

3 Answers 3

2

clientData.callback would literally try to access property callback on clientData. Think about clientData.callback being equivalent to clientData['callback'].

What comes after the . is not treated as a variable. Even if it were, the value of callback is a function. You can't use a function as property name. Property names are strings.

Sign up to request clarification or add additional context in comments.

Comments

2

When you create a function, think of the arguments as variables used in the function. When you do:

function getUserInput(firstName, lastName, callback)

and you call it with:

getUserInput ("Peter", "Pan", clientData.setUserName);

What implicitly happens at the top of the function is:

var firstName = "Peter";
var lastName = "Pan";
var callback = clientData.setUserName

Whatever you pass in as callback is referenced inside the function as callback. So if you pass in clientData.setUserName, it doesn't matter that it belongs to an object called clientData - it is still referred to as callback inside.

Comments

0

Try using:

function getUserInput(firstName, lastName)  {  
  clientData.setUserName (firstName, lastName);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.