如何从打字稿中的静态函数访问非静态属性

Sreginogemoh

我在嘲笑,User并且需要实现静态的static方法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
    }
}

但是我不能this从静态函数访问findOne有没有办法在打字稿中使用它?

大卫·谢瑞

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

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

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;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章