如何从typescript中的静态函数访问非静态属性

时间:2016-02-12 01:39:18

标签: properties static typescript

我在嘲笑User并且需要实现静态方法findOne,这是静态的,所以我不需要在我的调用类中扩展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有没有办法将它放在打字稿中?

2 个答案:

答案 0 :(得分:5)

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

但是,您可以从实例访问静态成员。这可能对你有用:

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

答案 1 :(得分:1)

试试这个

func Game(){
     var actionwait = SKAction.wait(forDuration: 3)
     var actionrun = SKAction.run({
          var randomIndex1 = Int(arc4random_uniform(UInt32(self.button.count)))
          var randomItem1 = self.button[randomIndex1]
          self.poupButtonImage.texture = SKTexture(imageNamed: self.images[randomIndex1])
          self.popupButtonImage.zPosition += 1
          self.continuationSequence.text?.append(randomItem1)
          self.winner.zPosition += 1
          self.winner.text = (randomItem1)
    })

    if(self.winner.text == self.buttonPressed.text){
        print ("Chicken Dinner")
        winner.run(SKAction.sequence([actionwait,actionrun]))
        Game()
    }
    else{
        print ("You lost")

    }

}

}