我对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
答案 0 :(得分:11)
您的代码存在一些问题。
考虑到这一点,固定代码将如下所示:
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', '!')