--- id: 587d7b8b367417b2b2512b53 title: Use class Syntax to Define a Constructor Function challengeType: 1 forumTopicId: 301212 --- ## Description
ES6 provides a new syntax to create objects, using the class keyword. It should be noted that the class syntax is just syntax, and not a full-fledged class-based implementation of an object-oriented paradigm, unlike in languages such as Java, Python, Ruby, etc. In ES5, we usually define a constructor function and use the new keyword to instantiate an object. ```js var SpaceShuttle = function(targetPlanet){ this.targetPlanet = targetPlanet; } var zeus = new SpaceShuttle('Jupiter'); ``` The class syntax simply replaces the constructor function creation: ```js class SpaceShuttle { constructor(targetPlanet) { this.targetPlanet = targetPlanet; } } const zeus = new SpaceShuttle('Jupiter'); ``` It should be noted that the class keyword declares a new function, to which a constructor is added. This constructor is invoked when new is called to create a new object.
Notes:
## Instructions
Use the class keyword and write a constructor to create the Vegetable class. The Vegetable class allows you to create a vegetable object with a property name that gets passed to the constructor.
## Tests
```yml tests: - text: Vegetable should be a class with a defined constructor method. testString: assert(typeof Vegetable === 'function' && typeof Vegetable.constructor === 'function'); - text: class keyword should be used. testString: assert(code.match(/class/g)); - text: Vegetable should be able to be instantiated. testString: assert(() => {const a = new Vegetable("apple"); return typeof a === 'object';}); - text: carrot.name should return carrot. testString: assert(carrot.name=='carrot'); ```
## Challenge Seed
```js /* Alter code below this line */ /* Alter code above this line */ const carrot = new Vegetable('carrot'); console.log(carrot.name); // => should be 'carrot' ```
## Solution
```js class Vegetable { constructor(name) { this.name = name; } } const carrot = new Vegetable('carrot'); ```