Home > Blockchain >  Inherited methods not printing expected values in Javascript
Inherited methods not printing expected values in Javascript

Time:09-14

In following code I'm expecting to print the values passed in to them as sentences. But instead program is printing the declaring function to the console.

class Person {

  constructor(firstName, lastName){
    this._firstName = firstName;
    this._lastName = lastName;
  }

  printName() {
    return `Hello my name is ${this.firstName} ${this.lastName}`
  }
}

class Staff extends Person {

  constructor(firstName, lastName, employeeID, location){
    super(firstName, lastName);
    this._employeeID = employeeID;
    this._location = location
  }

  printName(){
    return `${super.printName}, my staff ID is ${this.employeeID}`
  }

  facilitatedBranch(){
    return `My branch is ${this._location}`
  }
}

class ProjectManager extends Staff {

  constructor(firstName, lastName, employeeID, location, project){
    super(firstName, lastName, employeeID, location);
    this._project = project;
  }

  printPmInfo(){
    return `${super.printName} ${super.facilitatedBranch} my project is ${this._project}`
  }
}

let jhon = new ProjectManager('Jhon', 'Snow', 212 , 'Colombo', 'Blood Bank');
console.log(jhon.printPmInfo());

My expected output should be "Hello my name is Jhon Snow, my staff ID is 212 My branch is Colombo my project is blood bank"

CodePudding user response:

Problem

In your current code, you never call printName or facilitatedBranch.

console.log converts all arguments to string by default.

In JavaScript, function.toString() returns stringified body of the function.

printPmInfo(){
  return `${super.printName} ${super.facilitatedBranch} my project is ${this._project}`
}

Solution

Call printName and facilitatedBranch to actually run the functions and get the value.

printPmInfo(){
  return `${super.printName()} ${super.facilitatedBranch()} my project is ${this._project}`
}

Final version:

class Person {

  constructor(firstName, lastName) {
    this._firstName = firstName;
    this._lastName = lastName;
  }

  printName() {
    return `Hello my name is ${this._firstName} ${this._lastName}`
  }
}

class Staff extends Person {

  constructor(firstName, lastName, employeeID, location) {
    super(firstName, lastName);
    this._employeeID = employeeID;
    this._location = location
  }

  printName() {
    return `${super.printName()}, my staff ID is ${this._employeeID}`
  }

  facilitatedBranch() {
    return `My branch is ${this._location}`
  }
}

class ProjectManager extends Staff {

  constructor(firstName, lastName, employeeID, location, project) {
    super(firstName, lastName, employeeID, location);
    this._project = project;
  }

  printPmInfo() {
    return `${super.printName()} ${super.facilitatedBranch()} my project is ${this._project}`
  }
}

let jhon = new ProjectManager('Jhon', 'Snow', 212, 'Colombo', 'Blood Bank');
console.log(jhon.printPmInfo());

  • Related