"this" keyword Doubt in JAVASCRIPT


#1

// 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;
bob.setAge = setAge;

// make susan here, and first give her an age of 25

// here, update Susan's age to 35 using the method

I didn't understand the above code On line 8 (bob.setAge = setAge;) !
Why Should we write like that !
plz help me


#2

You shouldnt. In this situation youd just build a constructor.

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

var bob = new Person (30);

bob.setAge(31);

Just appease the exercise request relishing in the greater truth you now possess ; l


#3

But sir whats the use of that code any way ?


#4

You mean the "this" keyword, or the method, or the object?

Take a look here where i talk a little about getter methods:

Check out this one where i talk a bit more about getters & setters, why methods are important, and compare them to properties:


#5

bob.setAge = setAge;
Importance of this line of code in my Program ! :no_mouth:


#6

Because youre making a blank object.

var bob = new Object ();
/* bobs content
bob { }
*/

bob.age = 30;
/* bobs content
bob {
age: 30
}
*/

bob.setAge = setAge ();
/* bobs content
bob.age = 30;
bob {
  age: 30,
  setAge = function (newAge) {
    this.age = newAge;
  }
}
*/

#7

I had the same question but I think I finally made sense of it.

So, the first couple lines are just defining a function...then after you have the function set up and the bob object is initialized, bob only has properties. You want to add this method (setAge) to the bob object. To do that:

bob.setAge = setAge;

Javascript recognizes that setAge is a method (well function...) but then adds it to the bob object where it becomes a method of the bob object.

Ex.

Before bob.setAge = setAge;

var bob = {
age: 30,
}

After bob.setAge = setAge;

var bob = {
age: 30,
bob.setAge = function(newAge) { bob.age = newAge;},
};

As you can see (I wrote the method out on a single line to make it more apparent that much like a property, this method setAge is a "feature" of the bob object) it is a method since it performs an action.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.