Typescript: Calling a “method” of another class

后端 未结 5 2053
故里飘歌
故里飘歌 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:12

    I believe you need a constructor for classes in TypeScript. In the example I provide I made mine data holders, but it's not required. Additionally, your calculation functions need to return values. Also, in order to use Foo in an instance of Bar, you need to make an instance of Foo.

    class Foo {
       private data; 
       constructor(data: number) {
           this.data = data;
       }
    
       calcSomeThing(parameter:number): number {
          return parameter + 1;
       }
    }
    
    class Bar {
       private data;
       private foo:Foo = new Foo(3);
    
       constructor(data: number) {
           this.data = data;
       };
    
       calcOtherThing(): number {
          let result = this.foo.calcSomeThing(this.data);
          return result;     
       }
    }
    
    let bar = new Bar(5);
    console.log(bar.calcOtherThing()); // returns 6
    

提交回复
热议问题