简体   繁体   中英

Passing object with predefined props to class constructor es6

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"
    }) {

    }
}

PS I know how to define properties of objects. I want to know how to predefine properties.

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

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

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

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