0

How can I add a dynamic property with multiple attributes? I tried with backticks, but it did not work.

function User(userID){
   this.userID = userID;
   this.printUserDetails = function(){
       console.log(userID);
   }
}

const user=new User('A1234');

user.tokenID='jsessionID=12345678';

user.tokenValidity={
    startDate:07042020
    //What is the syntax to add end date here for e.g. endDate:08042020?
}
1
  • Do you want to do something like user.tokenValidity.endDate = 08042020? Or what do you mean by dynamic property. I see user is of type User. Do you want to add endDate to the constructor function User, or just to user? If the second option is true, you should be able to add it as I mentioned. If not, please provide more details as what is the error you get and what do you do to get the error. Commented Apr 7, 2020 at 11:13

2 Answers 2

2

It is working:

function User(userID){
   this.userID = userID;
   this.printUserDetails = function(){
       console.log(userID);
   }
}

const user=new User('A1234');

user.tokenID='jsessionID=12345678';

user.tokenValidity={
    startDate:07042020,
    endDate:5464644
}
console.log(user)

Sign up to request clarification or add additional context in comments.

Comments

1

Use Object.assign

function User(userID) {
  this.userID = userID;
  this.printUserDetails = function() {
    console.log(userID);
  }
}
const user = new User('A1234');

Object.assign(user, {
  tokenID: 'jsessionID=12345678',
  tokenValidity: {
    startDate: 07042020,
    endDate: 08042020
  }
})

console.log(user);
.as-console-wrapper { top: 0; max-height: 100% !important; }

I would actually make this a class, if you are using ES6.

class User {
  constructor(userId, properties={}) {
    this.userId = userId
    this.properties = properties
  }
  assignProperty(key, value) {
    Object.assign(this.properties, { [key] : value })
  }
  assignProperties(properties) {
    Object.assign(this.properties, properties)
  }
  printUserDetails() {
    console.log({
      userId : this.userId,
      properties : this.properties
    })
  }
}

const user = new User('A1234')

user.assignProperties({
  tokenId: 'jsessionID=12345678',
  tokenValidity: {
    startDate: 07042020,
    endDate: 08042020
  }
})

user.printUserDetails()
.as-console-wrapper { top: 0; max-height: 100% !important; }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.