Ricardo
Ricardo

Reputation: 151

Working with JS objects and functions

I'm a newbie in javascript and I'm wondering why bob.age is still 30 while age is 50 when I called it. I already set age to 50 in setAge that assigned 50 to this.age, which I know is a reference to bob.age, so age and bob.age should have the same value.

enter image description here

// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
    this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
// and down here we just use the method we already made

// change bob's age to 50 here
bob.setAge = setAge(50);

Upvotes: -1

Views: 288

Answers (3)

ChadF
ChadF

Reputation: 1758

There're several errors in your code/understanding, I'm going to start with why that is specifically wrong, and explain the concepts around it

var bob = new Object() is making bob a regular object.

your setAge function takes in a parameter. It sets this.age to be that value. However setAge is placed on the global scope. Therefore this -> window. Which is why when your typed in age in the global scope you got 50.

Jaromanda is correct, you need to place the function setAge onto the object bob.

If you're playing around with this you may be interested in the pseudoclassical instantiation style:

var Person = function(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.setAge = function(newAge) {
    this.age = newAge;
}

var bob = new Person ('Bob', 30);
bob.setAge(50);
bob.age; 
// 50

Upvotes: 6

Ricardo
Ricardo

Reputation: 151

The keyword this acts as a placeholder, and will refer to whichever object called that method when the method is actually used.

Look at the method setAge to see how this works. By using the keyword this, setAge will change the age property of any object that calls it.

Then when we say bob.setAge = setAge; it means whenever we type bob.setAge( ) this.age in the setAge method will refer to bob.age.

Upvotes: 1

Jaromanda X
Jaromanda X

Reputation: 1

bob.setAge = setAge(50);

all that is doing is setting the setAge property of bob to the result of calling setAge(50) - as setAge retunrs undefined, you've effectively set bob.SetAge = undefined. Perhaps what you intended to do was

bob.setAge = setAge; 
bob.setAge(50);

untested, but I think it's right

Upvotes: 3

Related Questions