5

I'm trying to get the name of derived type from base class method.I have classes as below:

export class Base{   
    public Add(value: any) {

    }
}

class Derived extends Base{
    public Add(value: any) {
        Base.prototype.Add.call(this, value);
    } 
}

I tried using $.type(this) inside Add() of Base class which gives type as object.But while debugging code type of this is shown as "Object (Derived)".

Is there any way to get this??

Swarna Latha
  • 1,004
  • 12
  • 21
  • If you don't mind me asking, what is your reason in doing this is? There might be a better way of doing things than the base class being aware of the derived class' name. – David Sherret Jan 29 '14 at 17:56

3 Answers3

7

You need to use the name property of constructor, like so:

class Base {   
    public Add(value: any) {
        alert(this.constructor["name"]); // alerts 'Derived' in this example
    }
}

class Derived extends Base {
    public Add(value: any) {
        super.Add(value); // use super to call methods on the base class
    }
}

(new Derived).Add('someValue');
David Sherret
  • 101,669
  • 28
  • 188
  • 178
0

First, you've not defined inheritance in your snippet. Use extends to create class inheritance in Typescript.

class Derived extends Base {
..

Second - to access base class you can use super keyword:

public Add(value: any) {
   super.Add.call(this, value);
} 
Anatolii Gabuza
  • 6,184
  • 2
  • 36
  • 54
  • Sorry.I just left to put extends.Now i have edited my code.Is there any way to get derived class name?? – Swarna Latha Jan 29 '14 at 09:27
  • 1
    @SwarnaLatha Look at [How to get object name](http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript) implementation. – Anatolii Gabuza Jan 29 '14 at 09:29
0

Each Object has a constructor function and you can look at its name property.

class Alpha { }
var a = new Alpha();
alert((<any>a).constructor.name);  // Alpha

link

You'll note I had to cast a to any. The constructor property isn't defined in lib.d.ts and I assume that's because its use is discouraged. Minification will also change the result. I would only use this for debugging purposes.

Jeffery Grajkowski
  • 3,982
  • 20
  • 23