2

Why isn't this code working? I'm trying to use the method to add up the properties and then assign the added up properties to its own value.

function howLongILivedSomewhere(college, home1, home2) {
    this.birthHome = 18;
    this.college = college;
    this.home1 = home1;
    this.home2 = home2;

    this.calcYearsAlive = function() {
    return birthHome + college + home1 +home2;
    };

    this.yearsAlive = calcYearsAlive();
}

var me = new howLongILivedSomewhere(4, 2, 3);

console.log(me);
Orbers
  • 79
  • 6

2 Answers2

1

You missed this keyword during your method / property call. Try like below.

  function howLongILivedSomewhere(college, home1, home2) {
    this.birthHome = 18;
    this.college = college;
    this.home1 = home1;
    this.home2 = home2;

    this.calcYearsAlive = function() {
      return this.birthHome + this.college + this.home1 + this.home2;
    };

    this.yearsAlive = this.calcYearsAlive();
}

var me = new howLongILivedSomewhere(4, 2, 3);

console.log(me.yearsAlive); // output: 27

What is this keyword?

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
How does "this" keyword work within a function?

Community
  • 1
  • 1
Venkat.R
  • 7,420
  • 5
  • 42
  • 63
0

Update the constructor to:

function howLongILivedSomewhere(college, home1, home2) {
    this.birthHome = 18;
    this.college = college;
    this.home1 = home1;
    this.home2 = home2;

    this.calcYearsAlive = function() {
      return this.birthHome + this.college + this.home1 + this.home2;
    };

    this.yearsAlive = this.calcYearsAlive();
}

var me = new howLongILivedSomewhere(4, 2, 3);

console.log(me);

Use this keyword when you need to access the object properties (see here more details).

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41