繁体   English   中英

Javascript ES6 - 如何向 object 添加动态属性?

[英]Javascript ES6 - How to add dynamic property to an object?

如何添加具有多个属性的动态属性? 我尝试使用反引号,但它不起作用。

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?
}

这是工作:

 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)

使用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; }

如果您使用的是 ES6,我实际上会将其设为 class。

 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; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM