Help with constructor functions JS

I wanna do a character rating system with constructor, there are Like points and bonus points, and then thos points are added into a single number

I’m having problems, this is what I already have, thanks



function Points(bonus, like) {
    this.bonus = bonus;
    this.like = like;
    this.changePoints = function (bonusChange, likeChange) {
        this.bonus = bonusChange;
        this.like = likeChange;      
    }    

    this.sumPoints = function(){
        this.total = bonusChange + likeChange;
     }
};


var pointsBase = new Points(0,15);

What problems are you having?

What are you expecting the above code to do that it does not do?

I want to rate something

Give it a LIke rate like 10 for example

Then give it a bonus of 5 for example, having those two numbers I wanna add them and have a final number, 15.

It can be donde in a single constructor fuction and then calling it? I wanted to try myself but I’m stuck.

You can’t access values inside other functions, they only exist inside the function. If I write it out slightly differently (still same logic), is it any clearer why what you’ve written can’t work? (I don’t think you’ve meant to write what you have btw)

var bonus;
var like;

function changePoints(bonusChange, likeChange) {
  bonus = bonusChange;
  like = likeChange;

function sumPoints () {
  // These two things don't exist, so this can't work
  return bonusChange + likeChange;
}

I was just trying to do something with constructors so, sorry if it’s a little confusing, but I’m starting with programming.

I just wanna know how it can be done so I absorb the syntax logic to my future studies.

So basically, if you can scrap all my code, but help me, I don’t mind lol, I just wanna learn

How you do it isn’t really relevant:

 this.changePoints = function (bonusChange, likeChange) {
        this.bonus = bonusChange;
        this.like = likeChange;      
    } 

this.sumPoints = function(){
      this.total = bonusChange + likeChange;
    }

These are two different functions. You can’t access variables that are declared only within one function in a different function. bonusChange + likeChange is trying to sum two things that a. don’t exist, and b. aren’t the things you want to sum.

The variables declared outside the functions (this.bonus and this.like), that’s fine, you can access those anywhere inside that Points function

1 Like