如何从打字稿中的静态函数访问非静态属性 [英] How to access non static property from static function in typescript

查看:40
本文介绍了如何从打字稿中的静态函数访问非静态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在模拟 User 并且需要实现静态方法 findOne 是静态的,所以我不需要在我的调用中扩展 User班级:

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

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

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

推荐答案

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

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

这篇关于如何从打字稿中的静态函数访问非静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆