Reputation: 15457
How do I find an object from within my class?
This is my stand-alone JavaScript component:
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);
}
In the client code, I have the following:
User("John", "Smith");
User("Jane", "Doe");
Upvotes: 0
Views: 77
Reputation: 69663
Usually you would create a separate class UserManager
. This class would be the only way to access users. Other classes would call userManager.createUser(name)
to create a new user or userManager.findUser(name)
to get an existing one. Ideally, the User class would be local to the manager, so no other classes can create instances directly. Whenever the UserManager creates a new User
in the createUser
method, it would add that user to an internal userList
before returning it. findUser
would then search that userList
.
Alternatively, you could add the array of created users as a static variable to the User
class. A static variable is a variable which is assigned to the class itself, not to its individual instances. Static variables are created and accessed with the syntax Classname.variable
, so in your case User.ALL_USERS
.
Upvotes: 2