ShowstopperCode1
ShowstopperCode1

Reputation: 130

Es6 Classes with curly braces

I have seen this in a codebase that I am working on that uses es6, but don't fully understand why there are curly brackets. I haven't seen any examples on the web that go into detail on this. Any thoughts, examples?

let aNewElement = new OldElement({theObject: 1})

Upvotes: 0

Views: 458

Answers (2)

Mark
Mark

Reputation: 92440

You can pass arguments to the constructor of es6 classes just like regular functions. These can be a simple value like a number, string — but it can also be an object, or even another function. In the example you showed, you are passing an object in using object literal notation: {theObject: 1}. So in the class you might take that object and do something like assign it to a property. For example:

class OldElement{
    constructor(someArg) {
        // this expects the argument to be an object with a 'theObject' property
        // so you can use it any way you want.
        console.log(someArg.theObject) // log it
        this.obj = someArg.theObject   // or save it to a property
    }
}

// pass in an object to the constructor
let aNewElement = new OldElement({theObject: "hello"})

// see the property we saved:
console.log(aNewElement.obj)

Upvotes: 2

Eduardo Martínez
Eduardo Martínez

Reputation: 360

Because it uses an object (associative array) as parameter in the instance of the class.

Same as:

let param = { theObject: 1 };
let aNewElement = new OldElement(param);

Upvotes: 4

Related Questions