1

I am trying to change the value of a global variable by declaring it at the constructor and then initializing it with a value in a function. What I am trying is quite similar to the code which I have typed here. The code executes but nothing gets printed. Can someone tell me what is happening?

class Sample{
  constructor(){
    let joey ="";
  }

  fire(){
    joey ="Yo";
    console.log(joey);
  }
}
1
  • does joey belongs to global or the sample class of the constructor? How are you calling printing it (calling the method?) Commented Sep 16, 2018 at 5:08

3 Answers 3

3

use "this" keywords for declare a global variable in constructor.

class Sample{
 constructor(){
    this.joey ="";
 }

 fire(){
    this.joey ="Yo";
    console.log(this.joey);
 }
}
Sign up to request clarification or add additional context in comments.

Comments

0

When working with classes, use "this" operator and assign values to "this" object as scope of "let joey" is not global(read "let" scoping) the way you defined it. See below -

class Sample{
 constructor(){
    this.joey ="";
 }

 fire(){
    this.joey ="Yo";
    console.log(this.joey);
 }
}

Comments

0

The variable joey is not contained within the scope of fire.

When you create an object (in this case an instance of the class Sample) you can set the properties of that object using the this object as it is a reference to the current object. If you use letorvar the variable will be contained to the function it is declared in (in this case constructor).

class Sample{
 constructor(){
  this.joey ="";
 }

 fire(){
   this.joey ="Yo";
   console.log(this.joey);

 }
}
let test = new Sample();
test.fire();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.