1

C# has a feature that we can set the class instance properties on the element creation (without a constructor). like this:

var Joe = new Person() {
    Age = 36,
    Weight = 83
}

Do we have a similar thing in JS and PHP?

JS something like:

var ActionBox = document.createElement("div") {
    className: "ActionBox"
};
0

1 Answer 1

2

You can do this by using Object.assign. It copies the properties of the source object and assigns them to the target object and returns the modified target.

var ActionBox = Object.assign(document.createElement("div"), {
    className: "ActionBox"
});

console.log(ActionBox);

Sign up to request clarification or add additional context in comments.

2 Comments

Very well, is it performance-friendly?
@Movahhedi That question depends on what you're measuring against; there aren't any alternatives that allow this kind of syntax. But if you're curious you could always check how the benchmark holds up against looping over the object and manually assigning the properties. benchmark

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.