Home > Software engineering >  How to define a class and using data from outside
How to define a class and using data from outside

Time:11-21

I have a class like this

class classname 
 {
  getuser(){}
  deleteuser(){}
 }

there are a list of users, defined out of the class like this

let user =[
 {id:1,name:"username},
 {id:2,name:"username},
]

Already I have a code with functions that work very well. But I have a problem accessing the list of users inside the class. Do I need to create a contractor?

CodePudding user response:

Do I need to create a contractor?

Yes Of course it must, When you're dealing with OOP every class has constructor even you don't create it, it has by default!

I have a problem accessing the list of users inside the class.

Try to declare it before and create your User objects, Then Add them up to the list of users, Play around with them by getting and deleting.

class User {
  constructor(id, name, isVerified) {
    this.id = id;
    this.name = name;
    this.isVerified = isVerified;
  }
  static getUser(id) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        let user = users.find((user) => {
          return user.id == id;
        });
        if (user) resolve(user);
        else reject("User not found!");
      }, 2000);
    });
  }
  static deleteUser(id) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        let user = users.find((user) => {
          return user.id == id;
        });
        if (user) {
          users = users.filter((user) => user.id !== id);
          resolve("User deleted successfully!");
        } else reject("user not found");
      }, 2000);
    });
  }
}
let users = [];
const u1 = new User(1, "Armin", true);
const u2 = new User(2, "Vahid", true);
const u3 = new User(3, "Steve", false);
users.push(u1, u2, u3);
console.log(await User.getUser(1)); //{ id: 1, name: "Armin", isVerified: true }
console.log(await User.deleteUser(3)); //User deleted successfully!
console.log(users); //[{id: 1, name: 'Armin', isVerified: true}, {id: 2, name: 'Vahid', isVerified: true}]
console.log(await User.getUser(3)); //User not found!

CodePudding user response:

I don't recommend using values outside of the a class. The reason for this is that the class doesn't have a way to know if any values are changed or manipulated outside if the instance. Keeping the values as a part of the class will allow every instance to own it's own set of data. For example, you can help multiple sets of users that aren't related in any way, but should still be manipulated with the same methods.

If you need the class to handle the users, then you could pass the users to the class with a constructor or through methods of your own. For example: addUser(id, name) {}

In the example below I've chosen the latter.

You don't need a constructor. Only if you have logic that has to be called whenever you create a new instance of the class, like setting up values and properties.

class Users {
  list = [];
  
  add(id, name) {
    this.list.push({
      id,
      name
    });
  }
  
  get(id) {
    return this.list.find(user => user.id === id);
  }
  
  delete(id) {
    this.list = this.list.filter(user => user.id !== id);
  }
}

// Create users instance.
const users = new Users();

// Add two users.
users.add(0, 'Foo');
users.add(1, 'Bar');
console.log('All users', users.list);

// Get a single user
const userBar = users.get(1);
console.log('User Bar', userBar);

// Delete a single user.
users.delete(0);
console.log('All users after deletion', users.list);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related