The "this" Keyword


#1

its cannot work , need help .

https://www.codecademy.com/courses/spencer-sandbox/2/4?curriculum_id=506324b3a7dffd00020bf661#



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
bob.setAge = setAge;
  
// change bob's age to 50 here

var bob = new Object();
bob.age = 50;
bob.setAge = setAge;



8.15 - The This Keyword! (Yes ... another one!)
#2

why did you write again these lines?

var bob = new Object();
bob.age = 50;
bob.setAge = setAge;

you just need to call the setAge on bob with 50 as an argument.

ObjectName.methodName(arg)


#3

tnx , its done.
Actually i could not understand the following line , thats why problem .

bob.setAge = setAge;


#4

so now you’ve understand :slight_smile:


#5

yap , but it will be better if u explain the line

bob.setAge = setAge;


#6

bob.setAge = setAge;

simply here you just set setAge method to setAge property on bob object.

Don’t confuse about property name.you can take any name here.for example:

bob.s= setAge; //here s is a property name

now you call that method like

bob.s(50);

It means whenever we type bob.s(), this.age in the setAge method will refer to bob.age

you can use same method on another object too.for example

var pop=new Object();
pop.s=setAge

I hope you’ve understand now :slight_smile:


#7

yap , thank u …:smiley:


#8

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