打字稿:调用另一个类的“方法”

时间:2016-02-22 15:20:29

标签: typescript

我对java- / type-script很新,我抓住了他们的概念。我想调用另一个类的方法。但是到目前为止我还没有成功。

export class Foo {
   calcSomeThing(parameter:number): number {
      //stuff
   }
}

class Bar {
   var foo:Foo = new Foo();

   calcOtherThing() {
      result = foo.calcSomething(parameter)
   }
}

calcSomething拨打foo calcOtherThing的正确方法是什么?

编辑:添加了foo

的实例

5 个答案:

答案 0 :(得分:11)

您的代码存在一些问题。

  1. Typescript区分大小写。所以“calcSomething”和“calcSomeThing”是两种不同的方法。
  2. 访问c​​als方法和属性的唯一方法是通过“this”关键字:this.foo
  3. 要定义类属性,请使用private / protected / public修饰符。或根本没有修饰符(与公众相同)。所以没有类似体内“var foo”的东西。
  4. 考虑到这一点,固定代码将如下所示:

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

答案 1 :(得分:8)

calcSomeThing是一种非静态方法/函数。创建Foo的实例以便能够调用它:

let foo:Foo = new Foo();
let result:number = foo.calcSomeThing( parameter );

永远不要在打字稿中使用var - let是你的朋友。

答案 2 :(得分:3)

我相信你需要一个TypeScript的类构造函数。在我提供的示例中,我提供了我的数据持有者,但这不是必需的。此外,您的计算函数需要返回值。另外,为了在Bar的实例中使用Foo,您需要创建一个Foo实例。

{{1}}

答案 3 :(得分:1)

在某些情况下可能并不正确,但是对于我正在开发的有角度的应用程序,我一直在使用服务-here's what angular says about them。然后,您可以这样称呼他们:

smile.service.ts

export class SmileService {

  addSmileMethod(input: string): string {
    return input + ' :)';
  }

}

smile-component.ts

import { SmileService } from './path/to/smile.service';

export class SmileComponent {

  constructor(private smileService: SmileService) { }

  ngOnInit() {
    // Using the service
    const smileString = this.smileService.addSmileMethod('Hello!');
    console.log(smileString);

    // Output is:
    // Hello! :)
  }

}

答案 4 :(得分:0)

这是另一个示例,但是具有共享的导出方法。

a.ts

export function sharedMethod(a, b, c) { return a + b + c }

export default class A {
   constructor(a, b, c) {
       this.concat = sharedMethod(a,b,c);
   };
}

b.ts中:

import { sharedMethod } from './a'

export default class B {
   constructor(a, b, c) {
       this.concat = sharedMethod(a,b,c)
   };
}

c.ts中的

import './a'
import './b'
new A('hello', 'world', '!')
new B('hello', 'world', '!')