Typescript: Calling a “method” of another class

后端 未结 5 2056
故里飘歌
故里飘歌 2021-02-13 11:51

I\'m pretty new to java-/type-script and I\'ve some troubles grasping their concepts. I would like to call a method of another class. However, I\'ve been unsuccessful s

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-13 12:03

    There are several problems with your code.

    1. Typescript is case sensitive. So "calcSomething" and "calcSomeThing" are two different methods.
    2. The only way to access cals methods and properties is through "this" keyword: this.foo
    3. To define class property use private/protected/public modifier. Or no modifier at all (that will be the same as public). So no things like "var foo" in the class body.

    Taking this into account the fixed code would look like this:

    export class Foo 
    {
        calcSomeThing(parameter:number): number 
        {
            //Stuff
        }
    }
    
    class Bar 
    {
        private foo:Foo = new Foo();
    
        calcOtherThing(parameter: number): number 
        {
                return this.foo.calcSomeThing(parameter)
        }
    }
    

提交回复
热议问题