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 so far.
export class Foo {
calcSomeThing(parameter:number): number {
//stuff
}
}
class Bar {
var foo:Foo = new Foo();
calcOtherThing() {
result = foo.calcSomething(parameter)
}
}
What is the correct way to call calcSomething
on foo
from calcOtherThing
?
edit: added an instance of foo
Create an instance of Foo to be able to call it: let foo:Foo = new Foo(); let result:number = foo. calcSomeThing( parameter ); Never use var in Typescript - let is your friend.
To class a method of another class, we need to have the object of that class. Here, we have a class Student that has a method getName() . We access this method from the second class SimpleTesting by using the object of the Student class.
If it's a static method (doesn't use any instance data), then declare it as a static method and you can directly call it. If it's an instance method, then you would typically create an object of type one and then call the method on that object (usually in the constructor).
The JavaScript call() Method It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
There are several problems with your code.
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)
}
}
calcSomeThing
is a non-static method/function. Create an instance of Foo
to be able to call it:
let foo:Foo = new Foo();
let result:number = foo.calcSomeThing( parameter );
Never use var
in Typescript - let
is your friend.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With