Search code examples
typescript1.4

How to call a method of a class from the same class


I got a class with 2 functions. One of them needs to call the other one both in the same class. How do you do that ?

class a
{
    func1(): string {
        return "test";
    }
    func2() {
        var aTest = this.func1(); // Get an undefined error ??
    }
}

Solution

  • What you have is completely valid (although func2 does nothing with aTest)

    I took what you have and tweaked a little to enable seeing output and renaming class a to class A. Take my code below and play with it here: http://www.typescriptlang.org/Playground

    class A
    {
        func1(): string {
            return "test";
        }
        func2() {
            var aTest = this.func1();
            alert(aTest);
        }
    }
    var a = new A();
    a.func2();