10

Task: I need to build a class in Typescript that calls some of it's own methods in it's own Constructor.

Problem: The Actual Code that the following Sample Code represents will Compile Successfully, but upon testing in the Javascript Console, it does not.

Sample:

export class volumeEQ
{
    constructor(ctx:any) 
    {
        this.ctx = ctx;         // Audio context saved into member variable of class
        this.setupAudioNodes(); // Sets up nodes made out of audio
    }

    setupAudioNodes()
    {
        this.sourceNode.connect(this.ctx.destination); // Connect to destination
    }
}

Technical: The Typescript Compiler does not have a problem with this.setupAudioNodes() but once called as Javascript within the Browser's Javascript Console I receive an error Uncaught TypeError: undefined is not a function. Effectively, this is an issue with Javascript's this. syntax and how it's easy to get confused with it. But because I'm developing in Typescript, I want a more Typescript style solution.

Question: How can I call a Class's Methods from it's Constructor in Typescript?

5
  • Calling methods from the constructor in the normal case is trivial, but there's not enough information in the code sample to reproduce the problem that you were running in to. Commented May 21, 2014 at 18:55
  • Calling methods from the constructor in the normal case should be trivial. It makes sense to be able to call a public method from the constructor of the same class. It makes sense that the Typescript Compiler believes it's possible and it's good that it compiles it successfully. It's to bad that Javascript's this. gets quite very confusing to work with. Commented May 21, 2014 at 19:03
  • @Jthora also youtube.com/watch?v=tvocUcbCupA&hd=1 Commented May 22, 2014 at 0:52
  • @basarat Excellent video, this helps me understand how I have been getting confused about this. Commented May 22, 2014 at 18:22
  • Voting to close since the question does not actually include information necessary to reproduce the problem claimed (see answers and OP's comments). Commented Mar 31, 2016 at 17:34

3 Answers 3

11

Here's how to call a method from the constructor:

class Thing {
    constructor(name: string) {
        this.greet(name);
    }

    greet(whatToGreet: string) {
        console.log('Hello, ' + whatToGreet + '!')
    }
}

var x = new Thing('world'); // Prints "Hello, world!"
Sign up to request clarification or add additional context in comments.

1 Comment

This answer makes sense.
7

The following is what I was looking for.

Solution Source:
How can I preserve lexical scope in TypeScript with a callback function

How to preserve Lexical Scope of this. in Typescript:

if the following declaration for methods isn't working:

export class myClass
{
    constructor()
    {
        var myString:string = this.myMethod(true);
    }
    
    public myMethod(useBigString:boolean) : string
    {
        if(useBigString)
        {
            return "bigString";
        }
        return "smlStr";
    }
}

which produces a method in javascript like the following:

myClass.prototype.myMethod = function (useBigString) {



Instead, Try declaring your methods this way:

export class myClass
{
    constructor()
    {
        var initString:string = this.myMethod(true);
    }
    
    public myMethod = (useBigString:boolean) : string => {
        if(useBigString)
        {
            return "bigString";
        }
        return "smlStr";
    }
}

which declares the method in javascript from within the constructor:

this.myMethod = function(useBigString) {



A drawback is that Method Syntax highlighting will not recognize this sort of definition, but it definitely Compiles and Works! This situation doesn't apply for Class Variables like it does for Class Methods.

4 Comments

Why not include a sample that actually reproduces the problem?
not sure how... I haven't gotten this far before in practicing Typescript. For context: I'm making tools and UI systems using cocos2d-JS. I'm programming with Sublime Text 3 and the Better Typescript package installed, also got the tsc build commands working too. I initially installed tsc using node.js. My classes are being called from an entry point constructor called by the cocos2d engine. I'm running this in Chrome Canary, because I'm practicing using the new webkitAudioContext(). The problem persists in regular Chrome as well.
You may know this by now, but you won't be able to override/overload your "myMethod".
What you do is like creating a static method
0

Research:

A Temporary Hack:

  • Create one class that has the methods you wish to call, but leave the constructor as basic as possible.
  • Next Create a second class that extends the first one.
  • Call the methods from within the Super Class. Example: super.myFunction();


Sample:

export class basicEQ
{
    constructor(ctx:any)
    {
        this.ctx = ctx;         // Audio context saved into member variable of class
    }
    setupAudioNodes()
    {
        this.sourceNode = this.context.createBufferSource(); // Create Buffer Source Node
        this.sourceNode.connect(this.ctx.destination); // Connect to destination
    }
}

export class volumeEQ extends basicEQ
{
    constructor(ctx:any)
    {
        super(ctx);
        super.setupAudioNodes(); // Use super, Not this
    }

}


Hack Explaination:
Use super. instead of this. for Method Calls inside the Constructor. Do it by Extending your Class so you may call super in the first place. Example: export class myUsableClass extends myBaseClass. Now, myBaseClass has all the Methods, and myUsableClass can call them from the Constructor.

My solution is a workaround to the actual problem, but it's good to know there is a way around the issue at all. If anyone else has another means to overcome the problem, do post! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.