The "this" Keyword


I got the concept of "this" keyword. I know that "this" acts as a placeholder for the object's name.

In the code below, I commented the line bob.setAge = setAge; to check what happens.
It showed - TypeError: bob.setAge is not a function. (In 'bob.setAge(50)', 'bob.setAge' is undefined)

Plz explain the purpose of the code bob.setAge = setAge;

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


The object doesn't have a name, it's a value. this refers to that value.

It sounds like you didn't create setAge before you used it to set bob.setAge

Kind of like:

var a = x;  // undefined
var x = 5;


setAge is a function but bob.setAge is not a function so we have to define bob.setAge to setAge?


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