Files
freeCodeCamp/curriculum/challenges/german/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.md
2023-01-26 09:03:56 -08:00

2.7 KiB

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
587d7b8b367417b2b2512b53 Verwende die Klassensyntax, um eine Konstruktorfunktion zu definieren 1 301212 use-class-syntax-to-define-a-constructor-function

--description--

ES6 bietet eine neue Syntax zum Erstellen von Objekten, die das Schlüsselwort class verwendet.

In ES5, an object can be created by defining a constructor function and using the new keyword to instantiate the object.

In ES6, a class declaration has a constructor method that is invoked with the new keyword. If the constructor method is not explicitly defined, then it is implicitly defined with no arguments.

// Explicit constructor
class SpaceShuttle {
  constructor(targetPlanet) {
    this.targetPlanet = targetPlanet;
  }
  takeOff() {
    console.log("To " + this.targetPlanet + "!");
  }
}

// Implicit constructor 
class Rocket {
  launch() {
    console.log("To the moon!");
  }
}

const zeus = new SpaceShuttle('Jupiter');
// prints To Jupiter! in console
zeus.takeOff();

const atlas = new Rocket();
// prints To the moon! in console
atlas.launch();

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.

Note: UpperCamelCase should be used by convention for ES6 class names, as in SpaceShuttle used above.

The constructor method is a special method for creating and initializing an object created with a class. You will learn more about it in the Object Oriented Programming section of the JavaScript Algorithms And Data Structures Certification.

--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.

--hints--

Vegetable should be a class with a defined constructor method.

assert(
  typeof Vegetable === 'function' && typeof Vegetable.constructor === 'function'
);

The class keyword should be used.

assert(code.match(/class/g));

Vegetable should be able to be instantiated.

assert(() => {
  const a = new Vegetable('apple');
  return typeof a === 'object';
});

carrot.name should return carrot.

assert(carrot.name == 'carrot');

--seed--

--seed-contents--

// Only change code below this line

// Only change code above this line

const carrot = new Vegetable('carrot');
console.log(carrot.name); // Should display 'carrot'

--solutions--

class Vegetable {
  constructor(name) {
    this.name = name;
  }
}
const carrot = new Vegetable('carrot');