Why doesn’t this work in Javascript?

Asked

Viewed 101 times

1

Why can’t I declare an "address" variable at the beginning of the class definition? And how the JavaScript can declare class variables using only this.nome_variavel?

class Pessoa {
    var endereco;
    constructor(nome, cpf){
        this.nome = nome;
        this.cpf = cpf;
    }
    printPessoa(){
        console.log('Nome: '+ this.nome);
        console.log('CPF: '+this.cpf);
        console.log('Endereco: '+this.endereco);
    }
    setEndereco(endereco){
        this.endereco = endereco;
    }
}
  • What will be the value of endereco if I instantiate Pessoa and not call the method setEndereco?

  • 1

    I believe Undefined because every variable not initialized in JS has this value as default

2 answers

1

Think of the class, as a structure similar to a JSON, JSON is a simple structure, similar to XML, it is worth noting that the class is a template/template, and the JSON object is a custom model with values or status:

Your class:

class Pessoa {

}

When you build a JSON, you will write something similar to this:

var pessoa = {propriedade: "valor"}

When you assign a method to a property in your class, you will do something similar to this:

class Pessoa { 

    propriedade: function() {

    } 

}

See the example below, imagine you tried to do the same with a JSON structure.

Have you ever seen someone make statements inside a JSON like this? You were able to identify the problem below?

//ISSO É IMPOSSÍVEL!!!
var pessoa = {

 var endereco;

} 

So... without declaring with "var" it will work, because it becomes a property, which is part of the scope of the keys of your class. And since in this case you have not assigned values or methods to this property, it becomes an undefined property:

pessoa.endereco //retornará undefined

Worth a read here to better understand

0

The class in javascript does not work with scope using var, if you remove var from the beginning of your address property it will work. But the starting Undefined value will be assigned.

Inside javascript it understands class as an object. For example

class ClasseObjeto {
 propriedadeA // undefined

 constructor(){
  this.propriedadeB = true;
 }

 getA() {
  return this.propriedadeA
 }
 setA( valor ) {
  this.propriedadeA = valor
 }

}

var Objeto = {
 propriedadeA: undefined,
 propriedadeB: true,
 setA: function( valor ){ this.propriedadeA = valor }
 getA: function(){ return this.propriedadeA }
}

Browser other questions tagged

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