1

I am trying to access the name defined in the constructor via a method, but it is returning undefined. Here is the simple code:

class Person {
  constructor(){
     let name = 'Tom';
    }
  logName(){
     console.log(this.name);
   }
}

let x = new Person();
x.logName();

5
  • 1
    Assign to this.name in order to assign it as a property of the instantiated object - else it's just a free variable, with all the usual scoping rules Commented May 27, 2018 at 9:51
  • let this.name = 'Tom' returns error in constructor. Why? Commented May 27, 2018 at 9:53
  • @yuvrajprogrammer Just this.name = "Tom";. this.name is not an identifier. Commented May 27, 2018 at 9:53
  • Don't use var or let to define properties Commented May 27, 2018 at 9:53
  • Thank you all for the explanation. Commented May 27, 2018 at 9:54

1 Answer 1

3

You need to define the name as a property of the object. In your case this.name

class Person {
  constructor(){
     this.name = 'Tom';
    }
  logName(){
     console.log(this.name);
   }
}

let x = new Person();
x.logName();

In your code, you've defined the variable name inside the constructor. It remains in there but doesn't escape.

Sign up to request clarification or add additional context in comments.

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.