Peter Boomsma
Peter Boomsma

Reputation: 9808

How to acces function from another class

I have two classes. A User and a Message class.

In my app.ts I have a array with 4 users,

let users: IUser[] = [
    new User({ id: 1, name: 'Jon Snow', status: Status.user }),
    new User({ id: 2, name: 'Arya Star', status: Status.user }),
    new User({ id: 3, name: 'Sansa Stark', status: Status.user }),
    new User({ id: 4, name: 'Joffrey Baretheon', status: Status.user })
]

I want to pass that array into my User class so I can use it in a function:

allUsers(users: IUser[]) {
    console.log(users);
}

But to do that I have to create a new instance of the User class in the app.ts:

let something = new User({ id: null, name: null, status: null });
something.allUsers(users);

But now I'm creating a empty instance just to acces the function. Isn't there a better way to acces a function inside a class?

Upvotes: 0

Views: 63

Answers (1)

basarat
basarat

Reputation: 276269

something.allUsers

If you have a member function of a class. You need to have an instance.

Perhaps you meant to make a static function:

class User {    
    private static created: User[] = [];
    static allUsers() {
        return User.created;
    }

    constructor(){
        User.created.push(this);
    }
}

new User();
new User();
console.log(User.allUsers()); // prints array of length 2

More

https://basarat.gitbooks.io/typescript/content/docs/classes.html

Upvotes: 2

Related Questions