Reading variables from an object that was created in another

Asked

Viewed 29 times

0

I’m creating an RPG and I found a problem: I can’t create monsters with levels.

My code is like this:

var xp = 0;

function MonsterCriado(entidade){    
    Lvl = Math.floor(Math.random() * (11 - 1) + 1);
    //quando um monstro nasce, é gerado um nivel para ele
}

function MonsterMorto(assassino, vitima){    
    xp += Math.floor(Math.random() * (18 - 3) + 3) * vitima.Lvl; 
    //quando eu matar o monstro eu qro ganhar xp baseado no seu nivel
}

The question that I’m unable to solve is: how to use the variable nivel of the monster in function MonsterMorto to earn Xp.

  • The variable Lv1 Voce means?

  • Why (11-1)+1 ?

  • Ss, qro use variable lvl

  • (11-1)+1 returns Random between 10 and 1

1 answer

0

You are creating the variable Lv1 inside MonsterCriado, but it doesn’t really save that value anywhere. (Well, actually, as it did not state the variable Lv1 it is believed in the global scope, which further complicates the history).

If you want the variable to be an attribute of the object being created, do this with the operator . and the special variable this.

This was at the interactive Javascript prompt:

function Monstro(){this.level = 2;}

m = new Monstro()
Monstro {level: 2}
m.level

2
  • I’ll try, I hope it works

  • It worked, vlww

Browser other questions tagged

You are not signed in. Login or sign up in order to post.