如何从静态函数访问非静态属性的打字稿
问题描述:
我嘲讽User
和需要实现静态方法findOne
这是静态的,所以我不需要在我的呼唤类extensiate 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;
}
}
一般来说,你不能从静态函数访问'this'。从类作用域调用静态函数,而从对象作用域调用成员函数。 –