Adding method to object(javascript)

Im currently doing precourse work for web development before I start the full [program and i’ve been stuck on a certain question for a couple days. I don’t want the answer to the question because i’m trying to understand the concept. 

This is the question: 

function exerciseTwo(userObj){
// Exercise Two: You will be given an object called ‘userObj’
// userObject will already have a key on it called ‘name’
// Add a method to userObj, called ‘greeting’.
// Using the keyword ‘this’, the greeting method should return the following string:
// ‘Hi, my name is ’ and the users name.
// eg: If userObj has a name: ‘Dan’, greeting should return: Hi, my name is Dan’
// NOTE: DO NOT create a new object.
// NOTE: DO NOT create a key called name the key is already on the object.

// Please write all of your code on the lines above.
return userObj;
}

If anybody can help me better understand this that would be great. I don’t want the answer I want to figure it out on my own. Thanks in advance.

I’m not certain how to help you “understand the concept”. I can provide a link to a web page which shows you how to do this (without giving you the exact answer) but it’s not clear to me if that would help your understanding or

not …

Yeah that would be great! I’ve been searching for information to help me better understand this question, but I haven’t found anything that is much help. I’m still pretty new to programming.  

Sorry for the delay …

This is what I found. The page may have some other useful info, but if you go down to the bottom there is a section “Adding a Method to an Object” and the example looks similar to the goals of your exercise.

Hi there! I am having the exact same issue. Did you manage to solve it? How did you go about it?

Hi, You need to add the method using the general format: 

 objectObject.keyToAdd  = function(){

      return “Some words”  + this.variableToReturn ;

}

For your case, add

userObj.greeting = function(){

    return "Hi, my name is " + this.name;

}

1 Like

Thank you sooo much! I have been struggling with that question as well and you just helped me out of alot of stress!