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