如何从typescript中的静态函数访问非静态属性

sre*_*moh 3 static properties typescript

我正在嘲笑User并且需要实现静态的静态方法findOne,所以我不需要User在我的调用类中扩展:

export class User implements IUser {

    constructor(public name: string, public password: string) { 

        this.name = 'n';
        this.password = 'p';
    }

    static findOne(login: any, next:Function) {

        if(this.name === login.name) //this points to function not to user

        //code

        return this; //this points to function not to user
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我无法this从静态函数访问findOne有没有办法在打字稿中输入它?

Dav*_*ret 7

这是不可能的.您无法从静态方法获取实例属性,因为只有一个静态对象和未知数量的实例对象.

但是,您可以从实例访问静态成员.这可能对您有用:

export class User {
    // 1. create a static property to hold the instances
    private static users: User[] = [];

    constructor(public name: string, public password: string) { 
        // 2. store the instances on the static property
        User.users.push(this);
    }

    static findOne(name: string) {
        // 3. find the instance with the name you're searching for
        let users = this.users.filter(u => u.name === name);
        return users.length > 0 ? users[0] : null;
    }
}
Run Code Online (Sandbox Code Playgroud)