JavaScript Essential Training

LinkedIn Learning : Morten Rand-Hendriksen

Code Samples

Object Blueprints

These are the JavaScript files from the chapter, Classes: Object Blueprints. The first file, Backpack.js, defines the class. The second, script.js, creates an instance of the class and then outputs the object and one of its properties to the console.

The Backpack.js file

	/**
	 * Creating classes:
	 *
	 * Class declaration: class Name {}
	 * Class expression:  const Name = class {}
	 */

	class Backpack {
	  constructor(
		// Defines parameters:
		name,
		volume,
		color,
		pocketNum,
		strapLengthL,
		strapLengthR,
		lidOpen
	  ) {
		// Define properties:
		this.name = name;
		this.volume = volume;
		this.color = color;
		this.pocketNum = pocketNum;
		this.strapLength = {
		  left: strapLengthL,
		  right: strapLengthR,
		};
		this.lidOpen = lidOpen;
	  }
	  // Add methods like normal functions:
	  toggleLid(lidStatus) {
		this.lidOpen = lidStatus;
	  }
	  newStrapLength(lengthLeft, lengthRight) {
		this.strapLength.left = lengthLeft;
		this.strapLength.right = lengthRight;
	  }
	}

	export default Backpack;

script.js

	/**
	 * Create a class for the Backpack object type.
	 * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
	 */
	import Backpack from "./Backpack.js";

	const everydayPack = new Backpack(
	  "Everyday Backpack",
	  30,
	  "grey",
	  15,
	  26,
	  26,
	  false
	);

	console.log("The everydayPack object:", everydayPack);
	console.log("The pocketNum value:", everydayPack.pocketNum);