0

I have a function which is defined before the object was created. This pre-defined function uses the 'this' keyword to change the value of a property in the object. Inside the object I have a method that calls the predefined method with one argument. However after calling this method and I try to print the value of the property that was supposed to be changed, it still remains the same. How do I fix this?

var setName = function(yourName){
    this.name = "Your name is " + yourName;
};

// create an object called `human`
var human = {
    name: "Nothing here yet",
    setHumanName: function(name) {
        setName(name);//Name should be changed now
    }
};

human.setHumanName("Emeka");
console.log(human.name); //this does not print the new value of name
2
  • 1
    Have you checked the JS console? If I recall it correctly, setName meaning for this is not what you expect, and you will be getting "invalid property" errors. Commented Apr 25, 2013 at 11:22
  • I get no errors, but when I try to console.log(name) inside the setHumandName function, it prints the correct value for name. Commented Apr 25, 2013 at 11:30

2 Answers 2

2

You should call the function in object context:

setHumanName: function(name) {
    setName.call(this, name);
}
Sign up to request clarification or add additional context in comments.

1 Comment

1

Just use

var human = {
    name: "Nothing here yet",
    setHumanName: setName // no invocation, only assigning the function
};

For explicitly invoking arbitrary functions on an object (so that their this keyword is set to that object) use the call method of the function.

1 Comment

Oh wow ^ That is the way we were told to do it but I either got an error message when I tried it previously or just forgot to do it this way. Now that looks a lot simpler than the other answer and more at my level. Thanks to the both of you that have posted answers

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.