Read variables from an object that was created in another [duplicate]

0

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

My code looks 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 I can not solve is how to use the variable nivel of the monster in the MonsterMorto function to win xp.

    
asked by anonymous 20.01.2017 / 14:12

1 answer

0

You are creating the variable Lv1 within MonsterCriado , but you do not actually save this value anywhere. (Well, actually, since you did not declare the variable Lv1 it is believed in the global scope, which further complicates the story).

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 here was at the Javascript prompt:

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

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

2
    
20.01.2017 / 14:19