smac89
smac89

Reputation: 43108

Using a pre-defined method to change a property of an object Javascript

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

Upvotes: 0

Views: 144

Answers (2)

Bergi
Bergi

Reputation: 664548

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.

Upvotes: 1

fardjad
fardjad

Reputation: 20404

You should call the function in object context:

setHumanName: function(name) {
    setName.call(this, name);
}

Upvotes: 2

Related Questions