skip to Main Content

I’m, writing the below code, I can’t understand how it is working. In C# or Java when we use base or super keyword it returns values but in typescript, I’m getting "undefined". If I use "this" instead of "super" it is working.

class Person {
    public firstName: string;
    public lastName: string;

    constructor(fn: string, ln: string) {
        this.firstName = fn;
        this.lastName = ln;
    }
}

class Customer extends Person {

    constructor(fn: string, ln: string) {
        super(fn, ln);
    }

    displayDetails() {
        console.log(`First Name :${super.firstName}tLast Name :${super.lastName}`);
    }
}

let c = new Customer("Pradeep", "Kumar");
c.displayDetails();

could someone explain the execution?

2

Answers


  1. Don’t use super but this

    displayDetails() {
        console.log(`First Name :${this.firstName}tLast Name :${this.lastName}`);
    }
    

    Playground

    Login or Signup to reply.
  2. See relevant docs at MDN: super

    The super keyword is used to access properties on an object literal or class’s [[Prototype]], or invoke a superclass’s constructor.

    Note that instance fields are set on the instance instead of the constructor’s prototype, so you can’t use super to access the instance field of a superclass.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search