I may not be doing this correctly, but here's my setup:
I have 2 classes in 2 files:
class-a.ts / classA
class-b.ts / classB
Then I have a namespace file (namespace.ts):
import { classA } from "./class-a";
import { classB } from "./class-b";
namespace App {
let a = new classA();
let b = new classB();
}
My question is, how do I call methods available in classA inside classB? Right now, if I try and call a.exampleMethod();
within b, it can't find the instance name. Shouldn't it be available?
There are a couple of ways you can sort this out:
extends
keyword In addition to the other answer, you could pass ClassB
into ClassA
on the constructor. The benefit here is that both ClassA
and ClassB
can be tested without depending on each other (you could pass a MockClassB
that implements IClassB
into ClassA
to test ClassA
, for example).
This can be adapted to suit your needs.
interface IClassB
{
SomeMethod(): void;
}
class ClassB implements IClassB
{
public SomeMethod(): void
{
// do something to update the UI
}
}
class ClassA
{
private classB: IClassB;
constructor( classB: IClassB )
{
this.classB = classB;
}
public SomeFunctionality(): void
{
this.classB.SomeMethod();
}
}
Then somewhere at the root of your application:
let iclassB: IClassB = new ClassB();
let classA: ClassA = new ClassA( iclassB );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.