Search code examples
javascriptfunctionclassobjectinstanceof

Create an instance of an object with the help of function (dynamically), on event triggers


I want to create an instance of an user Object containing the name, age etc.. prop. I just given a form to be filled by user and with that details i want to create his instance of an object dynamically (with that person own name i.e; user). For that i used function like shown below, but i'm facing this error . Thanks for the help in advance

class MainUser{
  constructor(name,age){
    this.name=name;
    this.age=age;
  }
}
function createUser(user, name, age){
  let user = new MainUser(name, age);
}

I'm getting this error Uncaught SyntaxError: Identifier 'user' has already been declared


Solution

  • You have the variable user as an parameter in the function-definition of createUser, and with let user you are trying to re-declare that parameter/variable. You have three options depending on what you try to achieve.

    1. rename the user-parameter of the function
    2. rename the user variable for your object inside the function
    3. remove the let to use the parameter of the function

    class User {
      constructor(name, age){
        this.name=name;
        this.age=age;
      }
    }
    
    let user = null;
    function createUser(name, age){
      user = new User(name, age);
    }
    createUser('Alice', 32);
    
    console.log(user);

    Another approach you can use:

    class User {
      constructor(name, age){
        this.name=name;
        this.age=age;
      }
    }
    
    function createUser(name, age){
      let userObject = new User(name, age); 
      return userObject;
    }
    let user = createUser('Bob', 31);
    
    console.log(user);

    For creating a variable with a dynamic name inside the current scope you can use the following:

    class User {
      constructor(name, age){
        this.name=name;
        this.age=age;
      }
    }
    
    function createUser(user, name, age){
      this[user] = new User(name, age);
      console.log(this[user]);
      console.log(test_user);
    }
    createUser('test_user', 'Charly', 42);