0

如何从我的班级中找到一个对象?

这是我的独立 JavaScript 组件:

function User(first, last){
    if (this instanceof User){
        this.name = first + " " + last; 

        //Is there a way here to find either User objects here? (John or Jane)
        //How would I changed to the desired User object and start working with it?
    }
    else return new User(first, last);
}

在客户端代码中,我有以下内容:

User("John", "Smith");
User("Jane", "Doe");
4

1 回答 1

2

通常你会创建一个单独的类UserManager。此类将是访问用户的唯一方法。其他类会调用userManager.createUser(name)以创建新用户或userManager.findUser(name)获取现有用户。理想情况下,User 类对于管理器来说是本地的,因此没有其他类可以直接创建实例。new User每当 UserManager在方法中创建 a时,它都会在返回之前createUser将该用户添加到内部。然后会搜索那个。userListfindUseruserList

或者,您可以将创建的用户数组作为静态变量添加到User类中。静态变量是分配给类本身的变量,而不是分配给其各个实例的变量。静态变量是使用语法创建和访问的Classname.variable,因此在您的情况下User.ALL_USERS

于 2013-10-28T13:46:42.477 回答