How to access non static property from static function in typescript

前端 未结 2 363
有刺的猬
有刺的猬 2021-01-18 18:39

I am mocking the User and need to implement static method findOne which is static so I do not need to extensiate User in my calling cl

相关标签:
2条回答
  • 2021-01-18 18:56

    try this

    export class test
    {
     private static t:test;
     private name:string;
     constructor()
     {
       t=this;
     }
    
    public static sample()
    {
       return t.name;
    }
    }
    
    0 讨论(0)
  • 2021-01-18 18:59

    It's not possible. You can't get an instance property from a static method because there is only one static object and an unknown number of instance objects.

    You can, however, access static members from an instance. This will probably be useful for you:

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题