简体   繁体   中英

javascript class instance object literal

Is there a shorthand way to add properties to an instance of a class in javascript?

Edit: The duplicate answers are about adding properties to an object not a class. I'm trying to make it easy for the user to add about 10-20 properties. I'm also trying to make sure they can't add their own properties but can only add values to the predefined properties. I don't know how to do that.

I have a javascript "class":

function Car(){
this.make="";
this.model="";
//...
}

To create an instance and add properties I would use:

var mycar = new Car();
    mycar.make="honda";
    mycar.model="civic";
    //...

Is there a shorthand way to create an instance and add the properties so I don't have to type "mycar." each time?

If your constructor doesn't do anything important, you can use Object.create() :

 function Car() { //... } console.log( Object.create( Car.prototype, Object.getOwnPropertyDescriptors( { make: 'honda', model: 'civic' } ) ) );

I wouldn't exactly call this "shorthand", but it is a single statement, and it omits invoking Car() if your constructor's body is redundant.

I'd personally recommend using Object.assign() within the body of your constructor :

 function Car(props) { /* to formally mimic behavior of default parameters specification */ // props = arguments.length < 1 || props === undefined ? {} : props; /* commonly used "good-enough" ES5 equivalent */ props = props || {}; Object.assign(this, props); } console.log( new Car({ make: 'honda', model: 'civic' }) );

Or ES6:

 class Car { constructor (props = {}) { Object.assign(this, props); } } console.log( new Car({ make: 'honda', model: 'civic' }) );

You should use the constructor's parameters:

function Car(make, model) {
  this.make = make;
  this.model = model;
}
var mycar = new Car("honda", "civic");

You can use Object.assign function.

 function Car() { this.make = ""; this.model = ""; } var mycar = new Car(); Object.assign(mycar, { make: "honda", model: "civic" }); console.log(mycar);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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