Home > Back-end >  How to use an object as an argument in JavaScript subclasses?
How to use an object as an argument in JavaScript subclasses?

Time:12-31

For example, if I have something like this:

class X{
    constructor({one, two}){
        this.one = one 
        this.two = two
    }
}

class Y extends X{
    constructor(props, three){
        super(props)
        this.three = three
    }
}

And I want to create an object with:

console.log(new Y({one: 1, two: 2, three: 3}))

Is it possible? I tried other ways like:

console.log(new Y({one: 1, two: 2}, 3))
console.log(new Y({one: 1, two: 2}, {three: 3}))

but they are uncomfortable.

CodePudding user response:

You can do that...
simply use Destructuring assignment

class X {
    constructor({one, two}) {
        this.one = one 
        this.two = two
    }
}

class Y extends X {
    constructor({three,...OneTwo}) {
        super(OneTwo)
        this.three = three
    }
    displaying() {
      console.log(this)
    }
}

let zz = new Y({one: 1, two: 2, three: 3})

zz.displaying()

  • Related