[javascript] ES6 class variable alternatives

ES7 class member syntax:

ES7 has a solution for 'junking' your constructor function. Here is an example:

_x000D_
_x000D_
class Car {_x000D_
  _x000D_
  wheels = 4;_x000D_
  weight = 100;_x000D_
_x000D_
}_x000D_
_x000D_
const car = new Car();_x000D_
console.log(car.wheels, car.weight);
_x000D_
_x000D_
_x000D_

The above example would look the following in ES6:

_x000D_
_x000D_
class Car {_x000D_
_x000D_
  constructor() {_x000D_
    this.wheels = 4;_x000D_
    this.weight = 100;_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
const car = new Car();_x000D_
console.log(car.wheels, car.weight);
_x000D_
_x000D_
_x000D_

Be aware when using this that this syntax might not be supported by all browsers and might have to be transpiled an earlier version of JS.

Bonus: an object factory:

_x000D_
_x000D_
function generateCar(wheels, weight) {_x000D_
_x000D_
  class Car {_x000D_
_x000D_
    constructor() {}_x000D_
_x000D_
    wheels = wheels;_x000D_
    weight = weight;_x000D_
_x000D_
  }_x000D_
_x000D_
  return new Car();_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
const car1 = generateCar(4, 50);_x000D_
const car2 = generateCar(6, 100);_x000D_
_x000D_
console.log(car1.wheels, car1.weight);_x000D_
console.log(car2.wheels, car2.weight);
_x000D_
_x000D_
_x000D_

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to ecmascript-6

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 where is create-react-app webpack config and files? Can (a== 1 && a ==2 && a==3) ever evaluate to true? How do I fix "Expected to return a value at the end of arrow function" warning? Enums in Javascript with ES6 Home does not contain an export named Home How to scroll to an element? How to update nested state properties in React eslint: error Parsing error: The keyword 'const' is reserved Node.js ES6 classes with require