Reputation: 512
I am trying to pass to my class constructor an object with predefined properties.
like this
class Test {
constructor({
a = "test a",
b = "test b"
}) {
}
}
P.S. I know how to define properties of objects. I want to know how to predefine properties.
Upvotes: 2
Views: 11608
Reputation: 11
The simple solution would be to pass the constructor and object during instantiation:
class Test {
constructor(obj){
this.a = obj.a;
this.b = obj.b;
}
};
const obj = {
a: 'value',
b: 'value'
};
const newtTest = new Test(obj);
Upvotes: 1
Reputation: 12240
It seems you want to pass one object to the constructor and have its properties assigned to single keys of the class. You can use destructuring for that this way:
class MyClass {
constructor({a,b} = {a:1,b:2}) {
this.a = a;
this.b = b;
}
}
Be aware that this is not safe for partially filled objects:
var instance = new MyClass({a:3});
// instance.b == undefined
Handling this could be done like so:
class MyClass {
constructor({a=1,b=2} = {}) {
this.a = a;
this.b = b;
}
}
Which results in:
var instance = new MyClass({a:3});
// instance.a == 3
// instance.b == 2
Upvotes: 15
Reputation: 9690
Like I said in my comment, there's an example right at the top of the documentation.
class Test {
constructor(/* put arguments here if you want to pass any */){
//Pre-define a and b for any new instance of class Test
this.a = "test a";
this.b = "test b";
}
}
Upvotes: 0