# Class Fundamentals

Salesforce Certified JavaScript Developer I · lesson 9

Six rules decide almost every class question.

Video: https://www.youtube.com/watch?v=7uVE9Jry8tg
Page: https://shipitcertified.com/learn/salesforce-javascript-developer/class-fundamentals/
Free slide PDF (free account): https://shipitcertified.com/learn/salesforce-javascript-developer/class-fundamentals/

## Chapters

- 0:00 [Class Fundamentals](https://www.youtube.com/watch?v=7uVE9Jry8tg)
- 0:32 [Quick recap: objects and their prototypes](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=32s)
- 1:05 [Six rules decide almost every class question](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=65s)
- 1:50 [One table holds the whole lesson](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=110s)
- 3:06 [A class is a special function that must exist first](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=186s)
- 3:55 [Using a class before its declaration throws](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=235s)
- 4:33 [Classes are sugar over prototypes](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=273s)
- 5:20 [One constructor initializes each instance](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=320s)
- 6:14 [Fields belong to each object; methods are shared](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=374s)
- 7:18 [Static members live on the class, not on instances](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=438s)
- 8:21 [Getters read like properties; setters take one value](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=501s)
- 9:18 [A # member is private to the class body](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=558s)
- 10:18 [extends builds a subclass on the parent](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=618s)
- 11:08 [this before super() is a ReferenceError](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=668s)
- 11:50 [A subclass method replaces the parent’s](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=710s)
- 12:31 [instanceof checks the prototype chain](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=751s)
- 13:28 [Six terms to say in your own words](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=808s)
- 14:11 [Predict each result, then run it in Node](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=851s)
- 15:11 [Eight questions, closed book](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=911s)
- 16:05 [What is logged when this code runs?](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=965s)
- 17:00 [ReferenceError, then true](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=1020s)
- 17:56 [Four cards, six rules](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=1076s)
- 18:33 [Now test it, then split code into modules](https://www.youtube.com/watch?v=7uVE9Jry8tg&t=1113s)

## Transcript

### Class Fundamentals (0:00)

Welcome to module two, lesson three: class fundamentals. This module is called Objects, Functions, and Classes, and it carries twenty five percent of the exam. Here we cover constructors, members, and inheritance. Classes are tested through short pieces of code that either work or throw an error. Our three keywords today are class, extends, and super. By the end, you will be able to read a class hierarchy, predict what runs, and spot the trap before you run it.

### Quick recap: objects and their prototypes (0:32)

Before we start, a quick recap from lesson two. First, spread and "assign" copy one level only. Nested objects are shared, not duplicated. Second, "freeze" is shallow too, so nested objects stay changeable. Third, inside a method, this is the object before the dot. And fourth, when a property is missing, JavaScript looks it up the prototype chain. Today we build on that same chain. Classes are a cleaner syntax for it, and they come with a few rules of their own.

### Six rules decide almost every class question (1:05)

This domain is twenty five percent of the exam. This lesson boils down to six rules, and there are eight topics you should be able to read in code. Rule one: declare a class before you use it. Rule two: one constructor, and methods that are shared. Rule three: static members stay on the class. Rule four: accessors, the getters and setters, read like properties. Rule five: private means private. And rule six: call super first, then use this. Rules one, three, and six produce most of the class questions, so we slow down there. We will also cover classes as sugar over prototypes, method overriding, and "instance of".

### One table holds the whole lesson (1:50)

This is the foundations slide, and one table holds the whole lesson. Every remaining slide is one row of this table, with an example, so pause here and read each row aloud. Class. The rule is that a class is not usable before its declaration. The trap is that calling new before the class throws. The safe habit is to declare first. Static. The rule is that it lives on the class, not on instances. The trap is that calling it on an object is not a function. The safe habit is to call it on the class. Hash name, a private member. The rule is that it is private to the class body. The trap is that outside access is an error. The safe habit is to expose a getter. Super. The rule is that a derived constructor calls super first. The trap is using this before super. The safe habit is to put super on line one. "Instance of". The rule is that it is true anywhere on the chain. The trap is thinking a parent is a child. The safe habit is to think from child to parent. One practical rule: declare first, call statics on the class, and call super before this.

### A class is a special function that must exist first (3:06)

Rule one: a class must exist before you use it. Start with how a class is defined. Look at the code. The first block is a class declaration, a class named Point, with a constructor that sets x. The second block is a class expression, stored in a constant named Rect, with an area method. And the last line shows that type of Point is the string function. You define a class with a declaration or a class expression. A class is a special function, and its body always runs in strict mode. Declarations behave as if they are not hoisted. They have the same temporal dead zone as let and const. So create the class before you call new on it. The exam point: a function declaration can be called early, but a class declaration cannot.

### Using a class before its declaration throws (3:55)

Here is the first trap. The wrong shortcut says declarations are hoisted, so new works anywhere. The correct exam test is this: a class has a temporal dead zone, so an early new throws a reference error. Look at the code. First, we call make later, and that is fine, because it is a function declaration. Next, we write new Early before the class Early line, and that throws a reference error. The function make later is declared at the bottom, and it still works, because functions are hoisted with their bodies. The practical rule: put the class above the first line that uses it.

### Classes are sugar over prototypes (4:33)

Classes are sugar over prototypes, which connects this lesson to the last one. Look at the code. Class Dog has a bark method, and we create one dog. Then d dot bark is the same function as Dog dot prototype dot bark, so that is true. But asking whether d has its own bark with "has own" gives false, because the method lives on the prototype, not on the object. And the last line calls Dog without new, which is a type error. So methods live on the prototype, and they are shared by all instances. The constructor becomes the function body. Prototype methods are non enumerable. And a class constructor cannot be called without new. The exam point: calling a class without new throws a type error.

### One constructor initializes each instance (5:20)

Rule two: one constructor initializes each instance. Look at the code. Class Person has a constructor with a default parameter, name equals Anonymous, and it sets this dot name. The introduce method returns a template string, Hello, my name is, followed by the name. When we call new Person with no argument and introduce, we get Hello, my name is Anonymous. The constructor creates and initializes the object. A second constructor in the same class is a syntax error. A constructor cannot be a getter, a setter, async, or a generator, but default and rest parameters are fine. If you omit it, a base class gets an empty constructor, and a derived class passes all of its arguments to super. The exam point: a class can define only one constructor. There is no overloading by argument count.

### Fields belong to each object; methods are shared (6:14)

Now fields and methods. Fields belong to each object, while methods are shared. Look at the code. Class Tile declares a field named id with no value, so it starts as undefined. Count equals zero is a field with a value, one per instance. Tap is an arrow function field, so each object gets its own function. And press is an ordinary method. We create two tiles, x and y. Then x dot tap triple equals y dot tap is false, because each has its own. But x dot press triple equals y dot press is true, because the method is shared. A field is an own property of each object, declared without const or let. A field with no value starts as undefined. A method lives once, on the prototype. And an arrow field gives each object its own bound function. That is useful, because a method passed along, like a click handler in a timeout, loses this, while an arrow field keeps it. The exam point: tap is false, press is true.

### Static members live on the class, not on instances (7:18)

Here is rule three, and it is a trap: static members live on the class, not on instances. Look at the code. Util has a static method, "fmt", that calls "to fixed" with one digit. Util dot "fmt" of two gives the string two point zero. But creating a new Util and calling "fmt" on it is a type error. In the second block, Weekly extends Report, and Weekly dot label still returns Report, because subclasses inherit public statics. So call a static as Class dot function, never on an instance. An instance call is not a function, which is a type error. Subclasses inherit public statics and can override them, calling the parent with super. From a method, use this dot constructor dot name to reach the class. In a static method, this works directly. The exam point: static members are called on the class, not on an instance. Statics suit utilities, caches, and fixed configuration.

### Getters read like properties; setters take one value (8:21)

Rule four: getters read like properties, and setters take one value. Look at the code. Class Msg has a private field, hash msg, set to hello world. The getter returns it, and the setter stores hello followed by the new value. We create an instance, assign cake to dot msg, and reading dot msg gives hello cake. But calling dot msg with parentheses is a type error, because the value is a string, not a function. A getter runs on read, takes zero parameters, and has no parentheses. A setter runs on assignment and takes exactly one parameter. Both are defined on the prototype and are not enumerable. So calling invoice dot total with parentheses, on a getter, is a type error. The exam point: write instance dot msg, not instance dot msg with parentheses. The fix is to read it as a property.

### A # member is private to the class body (9:18)

Rule five, another trap: a hash member is private to the class body. Look at the code. Class Acct has a private field, hash bal, set to ten, and a read method that returns it. Outside the class, a dot bal is undefined, because that is simply a different, missing property. And a with the string hash bal in brackets is also undefined. Calling a dot read gives ten. And writing a dot hash bal outside the class is a syntax error. Fields, methods, accessors, and statics can all use the hash. Outside access is an error, and bracket notation cannot reach it. Declare it up front. You cannot create a private field later by assignment. A private member cannot be deleted, and subclasses do not inherit it. The exam point: outside the class body a private field is an error, but the bracket string is just undefined. Reading a private element from an object that lacks it throws a type error.

### extends builds a subclass on the parent (10:18)

Now inheritance. The extends keyword builds a subclass on a parent. Look at the code. Asset has a constructor that sets tag. Laptop extends Asset with no constructor of its own, and new Laptop with L dash nine still has the tag L dash nine. In the second block, Dog extends Animal and writes its own constructor. It calls super first, then sets this dot name. The extends keyword links the child, and its prototype, to the parent. With no constructor, the default passes all arguments to the parent. A derived constructor that you write must call super. And this cannot be used before that call, or you get a reference error. The exam point: super must run before any use of this. The parent constructor is what creates this in a derived class.

### this before super() is a ReferenceError (11:08)

Here is the trap behind rule six. The wrong shortcut says to set this dot x first, then call super. The correct exam test is that the parent creates this, so call super first, then use this. Look at the code. Base sets this dot ready to true. Child extends Base. In the constructor, this dot x equals one comes before super, and that is a reference error. Then super runs. After that, this dot y equals two is fine. The practical rule: make super the first statement of a derived constructor. A derived constructor must also return an object or undefined, otherwise it is a type error.

### A subclass method replaces the parent’s (11:50)

Overriding: a subclass method replaces the parent's. Look at the code. Animal speak returns three dots. Dog extends Animal and defines its own speak, which calls super dot speak and adds the word woof. So new Dog dot speak returns three dots, then woof. The same name in the subclass means an override. And super dot method calls the parent version. Without super, only the child version runs. Arrow functions take super from the enclosing function. The exam point: super dot describe plus with trailer builds on the parent result. Override replaces, and super dot method builds on.

### instanceof checks the prototype chain (12:31)

Last topic: "instance of" checks the prototype chain. Look at the code. Class B extends class A. We create a, an A, and b, a B. Then b "instance of" B is true, and b "instance of" A is true. But a "instance of" B is false. And to negate, wrap the whole check in parentheses: not, a "instance of" B, is true. It is true when the class prototype appears anywhere in the chain. So a child instance is also an instance of its parent. But a parent instance is not an instance of the child. To negate, write not, open parenthesis, x "instance of" C. Without the parentheses, not x "instance of" C tests the wrong thing, because it is parsed as not x first. The exam point: b "instance of" A is true, and a "instance of" B is false.

### Six terms to say in your own words (13:28)

Here are six terms to say in your own words. A class declaration is class X, with a temporal dead zone like let and const. A constructor is the special method that initializes the instance. There is one per class. A field is a per instance property, and a static is a member on the class itself. Getters and setters are get and set accessors. A setter takes exactly one parameter. A private member is a hash name, accessible only inside the class body. And extends, super, and override create a subclass, call the parent, and replace a method. Pause the video now. Cover each card and explain the term aloud.

### Predict each result, then run it in Node (14:11)

Now the proof stage, starting with a lab. Predict each result, then run it in Node. Look at the hierarchy. Animal has a speak method. Dog extends Animal and overrides speak with super. Puppy extends Dog and adds nothing. And p is a new Puppy. Predict the five results on paper first. Take three minutes on your own, then run it in Node. Now the answers. One: p "instance of" Dog is true. Two: p "instance of" Animal is true, because the chain runs up through Dog. Three: a new Animal "instance of" Dog is false, because a parent is not a child. Four: p dot speak gives three dots, then woof. Puppy has no speak, so it finds Dog's, which calls the parent. Five: "has own" for speak on p is false, because the method lives on the prototype. A wrong prediction is the lesson. Go back to the slide that explains it.

### Eight questions, closed book (15:11)

Eight questions, closed book. Answer out loud, then I will reveal each one. One. New Box before class Box. Reference error. Two. What is type of an empty class expression? The string function. Three. Two constructors in one class? A syntax error. Four. A static "fmt", called on a new instance? A type error. Five. A getter named total, called as inv dot total with parentheses? A type error. Six. A with the string hash bal in brackets, when bal is a private field? Undefined. Seven. Using this before super? A reference error. And eight. A new A "instance of" B, when B extends A? False. How many did you get? Any miss, go back to the slide for that rule.

### What is logged when this code runs? (16:05)

Time for a practice question, taken from the question bank. This is a predict question. Pause the video and trace the code before you read the options. What is logged when this code runs? Base sets this dot ready to true. Child extends Base. In its constructor, a try block sets this dot x to one, and the catch logs the error name. Then super runs, and the constructor logs this dot ready. Finally, we call new Child. Option A: Type error, then true. Option B: Reference error, then undefined. Option C: true only. Option D: Reference error, then true. This question combines the super rule with try and catch. Work out whether this is usable in the try block. Pause now, and I will give you the answer on the next slide.

### ReferenceError, then true (17:00)

The answer is D. Reference error, then true. Here is why. Inside the try block, this dot x equals one runs before super, so this does not exist yet, and that throws a reference error. The catch logs its name. Then super runs the parent constructor, which sets this dot ready to true. The last line logs true. Now the wrong options. A says type error, then true. That gets the second part right, but this before super is a reference error, not a type error. B says reference error, then undefined. That forgets that super runs the parent constructor, so ready is true, not undefined. C says true only. That forgets that the try block does throw, so the catch logs an error name first. The takeaway: before super, this does not exist, so using it is a reference error.

### Four cards, six rules (17:56)

Let us consolidate: four cards, six rules. Declare. A class has a temporal dead zone, so declare it before new. Members. One constructor. Fields are per object, methods are shared, and statics live on the class. Access. Getters read without parentheses, and a hash member is private. Inherit. Call super before this. Override with super dot method. And a child is an instance of its parent. Remember: read the class from the top. Declaration, constructor, members, then the subclass.

### Now test it, then split code into modules (18:33)

That completes lesson three. Now test it, then split code into modules. The flow is: read it, predict it, test it. Your practice set is this lesson's questions in the bank. Do them now, closed book, and map any miss back to the slide that explains it. In the next lesson, Using JavaScript Modules, we split code into modules with import and export. See you there.
