Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

properties - How to access non static property from static function in typescript

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 class:

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

But I can't access this from static function findOne is there a ways of doning it in typescript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...