简体   繁体   中英

TypeScript: Run one class's methods from inside another class

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:

  • instantiate classA within classB (into a var, a field, depending on the scope you need)
  • use a mixin an make classB extend classA using the 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM