I am learning about classes in JavaScript. I have created a Student class and defined object inside a constructor function.
class Student {
constructor(firstName, lastName, age){
this.firstName = firstName
this.lastName = lastName
this.age = age
}
name(){
return `The student's name is ${firstName} ${lastName}`
}
}
const student1 = new Student('John', 'Carter', '26')
I want to print the statement in cmd written inside name() function that returns a statement. But I am getting nothing when I run the code.
Output I am expecting:
The student name is John Carter
>Solution :
You need to use this to access class property
name function return string, so you need to console.log to see the output
class Student {
constructor(firstName, lastName, age) {
this.firstName = firstName
this.lastName = lastName
this.age = age
}
name() {
return `The student's name is ${this.firstName} ${this.lastName}`
}
}
const student = new Student('John', 'Carter', 26)
console.log(student.name())