8

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?

1
  • Generally speaking you can't access this from a static function. Static functions are called from the class scope, whereas member functions are called from object scope. Commented Feb 12, 2016 at 1:43

2 Answers 2

16

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

-2

try this

export class test
{
 private static t:test;
 private name:string;
 constructor()
 {
   t=this;
 }

public static sample()
{
   return t.name;
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.