2016-02-12 103 views
0

我嘲諷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有沒有在打字稿中使用它的方法?

+0

一般來說,你不能從靜態函數訪問'this'。從類作用域調用靜態函數,而從對象作用域調用成員函數。 –

回答

1

這是不可能的。您不能從靜態方法獲取實例屬性,因爲只有一個靜態對象和未知數量的實例對象。

但是,您可以從實例中訪問靜態成員。這可能對你有用:

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