The Testing Academy · Class Notes Friday, 13 November (IST)
Live class · study guide

JavaScript constructors, private fields and static members

The constructor, a special function that runs once whenever new creates an object and sets up its first values; private # fields against public ones; classes for test code, a TestCase and an APIClient; and static fields and methods, which belong to the class and are shared by every object. Files 176 to 187, and a constructor for file 175.

By Pramod Dutta, The Testing Academy. Study notes from the Playwright 4x class of Friday, 13 November, built from the session recording, the batch repository, which received files 176 to 187, a constructor for file 175 and two cheat-sheet images in the last minutes of the class (commit "feat: add chapter 25 constructors and static"), and the Eraser notes deck, whose section for this class holds the constructor and attribute notes, a Credentials class, the static notes with the code of file 184, and the four topics to come. Every .js file on this page was run with Node 22, and the output shown is what it prints, errors included; local paths are made relative to the repo. File 183 is empty in the commit. In file 176, the user name and key passed in on line 13 are shown as placeholders, and so are a learner's name in file 182 and the four students' names in file 186; each file was run as shown. The commented lines switched on, the corrected copies of files 181 and 186, the changed lines shown with their outputs, and the private constructor snippet were written for this page, then run. None of the class's code makes a network request, and nothing on this page signs in anywhere.

Hides every output until you tap Reveal, so you can predict it first.
01

What this class covered

  • The constructor runs when an object is born
  • Private # fields and public fields
  • Two cars, four objects in memory
  • A TestCase class for Playwright
  • Counting attributes and behaviour
  • One APIClient for staging and prod
  • Static belongs to the class
  • Static and non-static methods
  • What is common is static
  • Outside a class, let; inside, none
  • Can a constructor be private?
  • Tasks: a test duration report class
  • A constructor is a special function that runs automatically, once, every time new creates an object, and sets up its initial values: file 175 makes two objects, so its line prints twice.
  • A JavaScript class has one constructor at most, and it is called constructor, not the class's name: a second one is SyntaxError: A class may only have one constructor.
  • A # field is private: only code inside the class can use it, and it must be declared in the class first. A public field can be made straight from the constructor with this..
  • this is the current object reference: in the constructor, it is the object being made.
  • One class, many objects: one TestCase class for every test case, one APIClient class for staging and for prod.
  • static belongs to the class, and every object shares it: read and call it on the class, as in TestRunner.totalTests and TestRunner.summary(). Fields set with this. belong to each object, and so do the methods without static.
  • Inside a class, members take no let, var or function keyword; a variable outside the class still needs its let.
02

The constructor runs when an object is born

This class went on from the 11 November notes, where file 175's class Person got its # fields; today it gets a constructor.

CAB: CONSTRUCTOR, ATTRIBUTES, BEHAVIOUR. EVERY NEW RUNS THE CONSTRUCTOR, ONCE THE CLASS IN FILE 175 class Person C, the constructor: line 14 constructor() { console.log(...) } A, the attributes: lines 3 to 6 #name #age #rollNo #phoneNo B, the behaviour: lines 21 and 22 eat(){} sleep(){} FIRST OBJECT, LINE 30 new Person() the constructor runs: line 1 below SECOND OBJECT, LINE 34 new Person() the constructor runs again: line 2 calls What file 175 prints I will be called whenever an object is created. from the new on line 30 I will be called whenever an object is created. from the new on line 34
File 175 with its new constructor: two objects, so the constructor runs twice, and its line prints twice.

The class opened with last class's task, setting up Playwright: a lot of people were able to do it, the instructor said. Then the class rolled back a little, to cover the remaining OOPS concepts in JavaScript: classes, objects, constructors, inheritance, encapsulation, polymorphism and abstraction, because they are very, very important, and so is how we will use them in TypeScript. Some parts of Playwright will come in between, in parallel, the instructor said, so that we do not get bored: the OOPS concepts are a little theoretical.

A class is a template for creating an object, with shared behaviour, the instructor recapped: it has attributes and behaviour, and an object is called an instance of the class. But one more thing is added, the instructor said: remember CAB as constructor, attributes and behaviour. How do you initialise the attributes? With a function that is called whenever an object is created, and this function is called the constructor. File 175 now has one:

175_Class.jsJavaScript
class Person { // (CAB)
    // Attributes | Instance variables |  Data members | Properties
    #name;
    #age;
    #rollNo;
    #phoneNo;

    // Constructor, Attributes, Behaviour - CAB


    // # Constructor
    //  **A special function that runs automatically, 
    // once, at the moment an object is born.**
    constructor() {
        console.log("I will be called whenever an object is created. ")
    }



    // Behaviour | Methods | Members Functions | 
    eat(){}
    sleep(){}
}


// # and we are not using function key in class for the f(n)

// CAB -> Class has the A, B

const pramod = new Person();
// Object -> new Person();
// Object Ref -> pramod

const amit = new Person();
Output
I will be called whenever an object is created. 
I will be called whenever an object is created. 

The constructor is a special function that runs automatically whenever an object is born, the instructor said, and the object is born where new Person() runs, as on line 30. It has the keyword constructor, and this one has no arguments at all. How many objects are created? Two, so it is called two times: two lines.

The deck calls the constructor the setup function: it runs automatically when you write new ClassName(), and it sets up the initial values. And JavaScript only allows one constructor per class, the instructor said, as the deck writes it too.

There are three types of constructor, the instructor said: the default constructor, the constructor with parameters, and the constructor with default values. File 175's, with no arguments, is the first kind; files 176 and 177 have the second.

03

Private # fields and public fields

A # FIELD STAYS INSIDE THE CLASS; A PUBLIC FIELD CAN BE USED OUTSIDE IT INSIDE THE CLASS, FILE 176 class Credentials #apiKey; line 2: private, declared first this.user = user; line 5: public, made right here this.#apiKey = key; line 6: set from inside the class getAPI(){ return this.#apiKey; } lines 8 to 10: read from inside OUTSIDE THE CLASS, LINES 13 TO 15 cred, made on line 13 cred.user prints <user>: it is public cred.getAPI() prints <api-key>, through the class's own method cred.#apiKey SyntaxError: Private field '#apiKey' must be declared in an enclosing class line 15 switched on: it stops before it runs new Take line 2 out, and the file stops on its line 5, this.#apiKey = key; SyntaxError: Private field '#apiKey' must be declared in an enclosing class this.user, on the line before it, needs no declaration: it is public.
File 176 with its real runs: only code inside the class can touch #apiKey, and it must be declared first.

Attributes have access modifiers, the instructor said: in JavaScript we have private and public, but there is no concept of protected; TypeScript has it. The deck's note reads the same: private and public, with protected struck out as not supported in JavaScript. A private attribute is given with the prefix #: prefixed with the hash, it becomes invisible outside the class, and nobody can read it or change it directly.

File 176, with the user name and the key passed in on line 13 shown as placeholders:

176_Con.jsJavaScript
class Credentials{
    #apiKey;

    constructor(user,key){
        this.user = user;
        this.#apiKey = key;
    }
    getAPI(){
        return this.#apiKey;
    }
}

let cred = new Credentials("<user>", "<api-key>");
console.log(cred.user);
// console.log(cred.#apiKey);
Output
<user>

Line 2 is an attribute, and the hash means it is private. In TypeScript there is a keyword, private, the instructor said, but this is JavaScript, and in JavaScript we have the hash. The constructor on line 4 has two arguments, so it is a parameterized constructor. At lines 1 and 2, the private value is not initialised yet; it gets its value on line 6, by using the keyword this, the current object reference: this. basically means my own variable.

Line 5 creates a variable directly in the constructor, with this., and it is public in nature, the instructor said, because there is no hash in front of it. Private means it is available only inside the class, in the constructor as well as in the functions; public is allowed outside too. So printing cred.user works.

JavaScript allows you to create an attribute directly like this, without declaring it outside first, the instructor said; but for a private one, it gives an error, and says to create it initially. Take line 2 out of file 176:

JavaScript
class Credentials{

    constructor(user,key){
        this.user = user;
        this.#apiKey = key;
    }
    getAPI(){
        return this.#apiKey;
    }
}
Output
25_Class_Object_Constructor/176_Con.js:5
        this.#apiKey = key;
            ^

SyntaxError: Private field '#apiKey' must be declared in an enclosing class

In TypeScript it will not happen, the instructor said: there, we will properly write it, a private API key of type string and a public user. JavaScript has a little tweak; it's a funny language.

Line 8's getAPI() returns the private key from inside the class. What is the beauty of private? If you try to print the user, you will be able to print it, the instructor said; the API key is hidden. Switch line 15 on, and there is the error:

JavaScript
console.log(cred.#apiKey);
Output
25_Class_Object_Constructor/176_Con.js:15
console.log(cred.#apiKey);
                ^

SyntaxError: Private field '#apiKey' must be declared in an enclosing class

The README's copy of file 176 calls the method the class wrote for it, which can read the key because it is inside the class:

JavaScript
console.log(cred.getAPI());
Output
<user>
<api-key>

The deck's version of this class has getAuthHeader() in place of getAPI(): it returns "Bearer " plus the key.

Did you notice, the instructor asked: here we do not have to use var or let, and we do not have to use the function keyword either.

04

Two cars, four objects in memory

EVERY NEW MAKES A NEW OBJECT IN MEMORY; THE NAME ON THE LEFT ONLY POINTS TO IT File 177: four references, four objects, the constructor run once for each references made on objects, each in its own memory hyndai_i10 line 10 Car { name: 'i10' } mg_hector line 13 Car { name: 'MG Hector' } i11 line 16 Car { name: 'i11' } Nexon line 17 Car { name: 'Nexon' } One constructor, run four times: each run fills in the new object, and line 6 gives it its name. hyndai_i10.name prints i10, and mg_hector.name prints MG Hector: two different objects.
The class's memory drawing, from a real run of file 177 that logs this as each object is made.

Another example of the constructor, the instructor said, and an interview question: somebody tells you to create a car class, and you have two cars. File 177:

177_IQ.jsJavaScript
class Car{
    // Constructor
    // Default vs Param

    constructor(assigned_name){
        this.name = assigned_name;
    }
}

let hyndai_i10 = new Car("i10");
console.log(hyndai_i10.name);

let mg_hector = new Car("MG Hector");
console.log(mg_hector.name);

const i11 = new Car("i11");     // constructor runs → "i10"
const Nexon = new Car("Nexon");
Output
i10
MG Hector

Is the constructor on line 5 parameterized or default? Parameterized, the instructor said. In Java, the name of the constructor should be the same as the class's name: that is a Java concept, and it is not true in JavaScript, the instructor said. Write it the Java way, a method named Car in place of constructor on line 5, and nothing sets the names, because nothing calls that method:

JavaScript
Car(assigned_name){
    this.name = assigned_name;
}
Output
undefined
undefined

The question came up twice later in the class: can we create a constructor with the class name in JavaScript, and should the constructor be the same as the class name? No, the instructor said both times: in JavaScript, no.

Then the memory. The real code starts at line 10, the instructor said: new Car("i10") creates a new object, a new memory. The value i10 goes to the constructor, and the name is assigned. The reference hyndai_i10 now points to that memory, where the name is i10, public in nature, so printing hyndai_i10.name gives i10. The moment you create the MG Hector, a new object is created, and mg_hector points to it, with the name MG Hector: a different object, which can have its own attributes and behaviour. Log this at the end of the constructor on line 5, and each object shows up as it is made:

JavaScript
constructor(assigned_name){
    this.name = assigned_name;
    console.log(this);
}
Output
Car { name: 'i10' }
i10
Car { name: 'MG Hector' }
MG Hector
Car { name: 'i11' }
Car { name: 'Nexon' }

We can create an unlimited number of objects, the instructor said: lines 16 and 17 add two more, four objects in all, and the constructor ran four times. Line 16's comment says "i10", but that object's name is i11, as the run shows.

Do you think we can have two constructors in JavaScript? No, the instructor said: JavaScript allows one constructor per class. File 178 keeps the attempt commented out. Switched on, Node refuses it before anything runs:

JavaScript
class Bad { 
    constructor(a) {} 
    constructor(b) {} 
}
Output
25_Class_Object_Constructor/178_IQ.js:3
    constructor(b) {} 
    ^^^^^^^^^^^

SyntaxError: A class may only have one constructor

In a nutshell, the instructor said: initial setup by using the constructor, then the attributes and the behaviour, C, A, B, to remember for life, or A, C, B, whatever you want to remember. File 179 lays it out in comments, with a constructor that has no arguments:

179.jsJavaScript
class Car{
  // Attibute


    // initial Setup
    constructor(){
        console.log("Hi,Object is created");
    }


    // Behaviour
}

obj_Ref = new Car();
Output
Hi,Object is created

Line 14 has no let. obj_Ref = new Car(); works here only because this file runs outside strict mode, as the repo's README warns: in strict mode, which ES modules and classes use, assigning to a name that was never declared is a ReferenceError. Below, "use strict"; is added as a new first line, so the error points at line 15. The constructor has already run when the assignment fails.

JavaScript
"use strict";
Output
Hi,Object is created
25_Class_Object_Constructor/179.js:15
obj_Ref = new Car();
        ^

ReferenceError: obj_Ref is not defined
05

A TestCase class for Playwright

A cheat sheet titled The Constructor Runs Once, at Birth. A blue card, labelled you call new, holds new TestCase with Login Test, PASS and P0. An arrow leads to a yellow machine with a lit lamp on top, labelled runs automatically and headed constructor(name, status, priority); inside, this.name = name;, this.status = status; and this.priority = priority;. An arrow leads to a green card, loginTest_ref, labelled a ready-made object, holding name Login Test, status PASS and priority P0. A banner at the bottom reads: One constructor per class.
From the batch repo's README: new calls the constructor, which fills in the new object, here the login test of file 180 (the sheet shortens its parameter names).

Now a real scenario, the instructor said: how we are going to keep a test case in Playwright. In Playwright we will create a test case class, with a constructor: every test case will have a name, a status code and a priority, the instructor said. In file 180 they are the name, the status and the priority:

180_REAL_PW.jsJavaScript
class TestCase{

    constructor(name_given, status_given, priority_given){
        this.name = name_given;
        this.status = status_given;
        this.priority= priority_given;
    }
    display(){
      console.log(this.name + " → " + this.status + " → " + this.priority);
    }
}

let loginTest_ref = new TestCase("Login Test","PASS","P0");
let signupTest_ref = new TestCase("Signup Test","FAIL","P1");

loginTest_ref.display();
signupTest_ref.display();
Output
Login Test → PASS → P0
Signup Test → FAIL → P1

Do not get confused, the instructor said: the names on line 3, such as name_given, can be anything. This class has a constructor plus attributes; is the constructor parameterized or default? Parameterized, and that was absolutely right, the instructor said. display() prints them all by using this.name, this.status and this.priority. The advantage: you can create an object for a login page, and one for a signup page, and if you display them, both will be different. What is the output, the instructor asked: both of them will be printed, and the run shows the two lines. So this becomes a test case class that you can use an unlimited number of times.

So declaring the attributes separately, at line 2, is not mandatory, a learner asked? Yes, it is not mandatory, the instructor said, because JavaScript is a funny language: you can directly do it in the constructor. In TypeScript, it will be mandatory.

What is the use of having a constructor in a Playwright class, a learner asked: what does it bring, instead of functions? A very important question, the instructor said. A constructor helps you assign default values: when a real object is created, the constructor is called, and the default values are assigned. If you do not assign them, you have to change them later, which you can also do. But the constructor sets up the values, so whenever you are getting started, you start with something, not zero: that is the beauty of the constructor.

06

Counting attributes and behaviour

File 181 is the private and public file, and the instructor asked: how many attributes does it have, and how many behaviours?

181_Private_Public.jsJavaScript
class Browser {
    constructor(name) {
        this.name = name;
        this.isOpen = true;
        console.log(name + " launched");
    }
    startBrowser() {
        console.log("starting the browser")
    }
    closeBrowser() {
        console.log("starting the browser")
    }
}
let chrome = new Browser("Chrome");
let firefox = new Browser("Firefox");
console.log(chrome.isOpen);
chrome.closeBrowser()
chrome.startBrowser()
Output
Chrome launched
Firefox launched
true
starting the browser
starting the browser

Two attributes, the instructor said, and the console.log on line 5 is not an attribute: it is a console message. Two behaviours, start and close, and one parameterized constructor.

The class has In file 181 Where
Attributes name, isOpen lines 3 and 4
Constructor constructor(name), parameterized line 2
Behaviour startBrowser(), closeBrowser() lines 7 and 10

closeBrowser() prints "starting the browser". Line 11 repeats line 8's message, a copy-paste slip that the repo's README points out, so the last two lines of the output are the same. Despite its name, the file has only public fields, as the README also notes: neither name nor isOpen has a #.

With line 11 corrected, in a copy kept outside the repo, closeBrowser() reads:

JavaScript
closeBrowser() {
    console.log("closing the browser")
}
Output
Chrome launched
Firefox launched
true
closing the browser
starting the browser
07

One APIClient for staging and prod

In Playwright, you will see a real API client a lot of times, the instructor said. File 182, with its method shown as get; in the repo, it carries a learner's name:

182_api.jsJavaScript
class APIClient {
    constructor(baseURL) {
        this.baseURL = baseURL;
    }
    get(path) {
        return this.baseURL + path;
    }
}
let staging = new APIClient("https://staging.api.com");
let prod = new APIClient("https://prod.api.com");
console.log(staging.get("/users"));
console.log(prod.get("/prod/users"));
Output
https://staging.api.com/users
https://prod.api.com/prod/users

The API client has a constructor with a base URL, the instructor said, a public URL that you can get and use directly: so you will see the staging URL and the production URL. The file only joins two strings; it sends no request.

What is .get, a learner asked. A method, the instructor said: a normal method, and its name is get; it can be anything, and there is no problem in that.

08

Static belongs to the class

A cheat sheet titled static vs instance. A blue card, class TestRunner, holds static totalTests = 4 and static passCount = 3, each tagged shared. Arrows lead from it to three green cards, t1, t2 and t3, holding the names loginTest, signTest and dashboardTest, each tagged own copy. Two boxes at the side read TestRunner.totalTests and t1.name. A banner at the bottom reads: static: one per class. instance: one per object.
From the batch repo's README: file 184's two counts sit once, on the class, and each object keeps its own name.

The base URL of file 182 belongs to the object, the instructor said: it is different for both objects, staging and production. But can there be a variable which is common for both, say a static variable with the value 10, the same for different objects? For example, both persons belong to the same company, or both of us belong to the same Playwright 4X batch. That is called static: it belongs to the class, not to the object, and it is shared with the objects automatically. Static becomes common to all the objects, and if any object changes it, it changes for the other objects too. The deck puts it the same way: static belongs to the class, not to individual objects, and if one object changes the value of the static, the other objects will also see the same value.

File 183 is empty in the commit. The code is in file 184, and the deck holds the same lines:

184_Static.jsJavaScript
class TestRunner{
        static totalTests = 0;
        static passCount = 0;
        constructor(name, passed){
            this.name = name;
            TestRunner.totalTests++;
            if(passed){
                TestRunner.passCount++;
            }
        }
}
let t1 = new TestRunner("loginTest", true);
let t2 = new TestRunner("signTest", false);
let t3 = new TestRunner("dashboardTest", true);
let t4 = new TestRunner("supportTest", true);
console.log(TestRunner.totalTests);
console.log(TestRunner.passCount);
console.log(t1.name);
console.log(t2.name);
console.log(t3.name);
console.log(t4.name);

// name,passed - non static
// totalTests, passCount - static
Output
4
3
loginTest
signTest
dashboardTest
supportTest

The keyword is static, the instructor said, and the values are initialised on lines 2 and 3. The constructor takes a name and passed: it stores the name, adds one to the total every time, and adds one to the pass count only if the test passed. On the iPad, each new created a new memory with its own name, while the two counts sat with the class. Logged after each of lines 12 to 15, the counts read:

Line Object Passed Total tests Pass count
12 t1, "loginTest" true 1 1
13 t2, "signTest" false 2 1
14 t3, "dashboardTest" true 3 2
15 t4, "supportTest" true 4 3

What is T1 seeing for the total after T3? Three, the instructor said: all of them are seeing the same value, because it belongs to the class. The final values: the total is 4 and the pass count is 3, while each object has its own name. Whenever something is static, it has the value at the level of the class; name and passed are non-static, the instructor said, and they change according to the objects.

Read a static field on the class. Every object shares TestRunner.totalTests, but an object does not read it through itself: added at the end of file 184, console.log(t1.totalTests); prints undefined. From anywhere, the one shared value is TestRunner.totalTests.

JavaScript
console.log(t1.totalTests);
Output
4
3
loginTest
signTest
dashboardTest
supportTest
undefined
09

Static and non-static methods

Now you tell me the output, the instructor said: file 185, an interview question, very similar to file 184, but with two important things here.

185_IQ.jsJavaScript
let a = 10;
class TestRunner {
    static totalTests = 0;
    static passCount = 0;
    constructor(name, passed) {
        this.name = name;
        TestRunner.totalTests++; // 1
        if (passed) {
            TestRunner.passCount++;  //1
        }
        console.log(a);
    }
    // non static fn
    pramod_fn() {
        return this.name;
    }
    static summary() {
        return TestRunner.passCount + "/" + TestRunner.totalTests + " passed";
    }
}
let t1 = new TestRunner("Login", true);
t1.pramod_fn();
console.log(TestRunner.summary());

// new TestRunner("Signup", false);
// new TestRunner("Cart", true);
// new TestRunner("Checkout", true);
// console.log(TestRunner.summary());
// console.log(TestRunner.pramod_fn());
Output
10
1/1 passed

Line 1 is a normal variable, the instructor said: it does not even belong to the class, it is outside, definitely non-static. Lines 3 and 4 are static. The name and passed in the constructor are non-static: they belong to the objects. The constructor prints a, so each object prints 10.

A function without static in front of it is a non-static function, such as pramod_fn() on line 14; summary() on line 17 is a static function. A static function can be called directly by using the class name, the instructor said. Can you call pramod_fn() directly by using the class name? No, because it is non-static in nature: it belongs to the objects. Line 22 calls it on the object t1, though it does not print what it returns.

The class's drawing had four objects, and the constructor was called four times. Switch on lines 25 to 29, which make the other three and then try the class name:

JavaScript
new TestRunner("Signup", false);
new TestRunner("Cart", true);
new TestRunner("Checkout", true);
console.log(TestRunner.summary());
console.log(TestRunner.pramod_fn());
Output
10
1/1 passed
10
10
10
3/4 passed
25_Class_Object_Constructor/185_IQ.js:29
console.log(TestRunner.pramod_fn());
                       ^

TypeError: TestRunner.pramod_fn is not a function

How do we call pramod_fn(), then? By creating an object, the instructor said: new TestRunner("Login", true).pramod_fn() creates an object but does not assign it to anything, and that also works. Ideally you assign it, as line 21 does, and call it with t1: if you are a good person, you will assign, the instructor said. With lines 21 and 22 replaced by the unassigned form, printed:

JavaScript
console.log(new TestRunner("Login", true).pramod_fn());
Output
10
Login
1/1 passed

To call summary(), do we have to use an object? No, the instructor said: we do not need an object or an object reference, and the class name, dot summary, calls it directly, as line 23 does.

Call Kind What happens
TestRunner.summary() static, on the class 1/1 passed
t1.pramod_fn() non-static, on an object returns Login
TestRunner.pramod_fn() non-static, on the class TypeError: not a function
10

What is common is static

Two panels on cream paper. Left, titled Shared by all, with the sublabel static: one blank terracotta banner above four identical grey school desks, with a line running down from the banner to each desk. Right, titled One per student, with the sublabel non-static: the same four desks with no banner, each holding its own small card with one terracotta bar, and every bar a different length.
The class's example of static: what is common to every student, the batch and the mentor, belongs to the class; each student's score belongs to each object.

One more real example, the instructor said, one all of you will be able to relate to: students of the Playwright 3X and 4X batches. What is common between them? Their college name, which is their Playwright automation batch: whatever is common becomes static. Is the name common? No, the name is different for each. The mentor's name will be static, because the mentor is the same for them. The score of your test is non-static, because a score is individual to a student. File 186, with the four students' names shown as placeholders:

186_REAL.jsJavaScript
class Student {
    static collegeName = "PW AT Batch";
    static mentorName = "prrammoddutta";


    constructor(name,score) {
        this.name = name;
        this.score = score;
    }
    static display() {
        console.log(this.name + " are part of the ", Student.collegeName + this.score)
    }
    nsf(){
        console.log(this.name);
    }
}
let studentA = new Student("studentA",80);
let studentB = new Student("studentB",91);
let studentC = new Student("studentC",87);
let studentD = new Student("studentD",99);
console.log(Student.collegeName);
console.log(studentA.name);
console.log(studentB.name);
Output
PW AT Batch
studentA
studentB
Member Kind In file 186
collegeName static "PW AT Batch", one for the class
mentorName static one for the class
name non-static one per student
score non-static 80, 91, 87, 99: one per student

Static or not, the instructor marked the methods too: nsf() is a non-static function, and display() is also a static function in this case.

A static method has no student to read. display() is never called in the file. Called the way a static method is called, on the class, it shows the slip that the repo's README points out: inside a static method, this is the class itself, so this.name is the class's own name, Student, and this.score is undefined.

JavaScript
Student.display();
Output
PW AT Batch
studentA
studentB
Student are part of the  PW AT Batchundefined

A method that reads one student's name and score belongs to the object. Without static, and called on an object, in a copy kept outside the repo, it prints that student's line:

JavaScript
display() {
    console.log(this.name + " are part of the ", Student.collegeName + this.score)
}

studentA.display();
Output
PW AT Batch
studentA
studentB
studentA are part of the  PW AT Batch80
11

Outside a class, let; inside, none

A small funda, the instructor said, in file 187:

187.jsJavaScript
let a = 10;
class Car{
    b;
    constructor(){
        console.log(a);
        this.b = 10;
    }
}
let obj= new Car();
let obj2= new Car();
Output
10
10

a, on line 1, does not belong to the class, the instructor said: it is a global kind of variable. b, on line 3, belongs to the class, and it is non-static. Can the constructor use a? Yes: each of the two objects prints 10. If it belongs to the class, we do not require let: in the class, we do not need a let variable or a constant, the instructor said. A class body does not even accept one; put let in front of b, and Node stops:

JavaScript
let b;
Output
25_Class_Object_Constructor/187.js:3
    let b;
        ^

SyntaxError: Unexpected identifier 'b'

So this marks your classes, objects and constructor, the instructor said.

12

Can a constructor be private?

Can we make a constructor private in JavaScript, a learner asked near the end. Even if you make it, in JavaScript it is not possible, the instructor said; in TypeScript, we are more interested, and we will see. There is no specific reason, to be honest, the instructor added: JavaScript was not initially created for the OOPS concept, it was created only for web elements and many more, and in TypeScript you will see more. And if you make it private, how will you create an object, and what is its real purpose? That is also true, the instructor said: if you make a constructor private, then there is no object, so it does not even make sense.

Tried in a snippet written for these notes, with a # in front of the constructor:

JavaScript
class Car {
    #constructor() {}
}
Output
25_Class_Object_Constructor/notes_private_constructor.js:2
    #constructor() {}
    ^^^^^^^^^^^^

SyntaxError: Class constructor may not be a private method
13

Tasks and announcements

  • Today's task: a test duration report class. The instructor picked it from the practice questions on the dashboard, thinking it can be done with a class: you are given the tests, each with its name and its time, and in the end you give the total time and the slowest test case. It is a real example, the instructor said, one that has come in interviews too, related to class, and we will eventually be creating this in the end. The TA is to check that it can be done through a class, and only then give the task to everyone, with proper instructions, if possible; the instructor thinks it can be done.
  • Doubts: the doubt thread is created. Put your questions into it.
  • Next class: encapsulation, inheritance, polymorphism and abstraction, the four more important concepts, the instructor said; the deck lists the same four. Getters and setters are supported in JavaScript too, the instructor said when a learner asked, and they come next class.
  • The code is pushed: "Code is already pushed," the instructor said. Files 176 to 187 are in the repo's 25_Class_Object_Constructor folder, and file 175's constructor is in 23_Class_Objects.
  • Tester Town: a chat feature, launched recently for you and still in beta mode, the instructor said. Playwright 4X is your group, and the 3X people are already talking. It is a simple town of testers with a lot of challenges here and there: you can move around, talk to other people, catch bugs (there are 24 bugs in the platform), and start an interview. If you do not have access, you will get it soon: it is rolling out slowly. LinkedIn is compulsory, because it makes your profile more genuine. It is a community: have discussions and ask questions. And it is a public platform, so make sure we follow all the guidelines.
  • One platform: the instructor is trying to bring everything onto app.thetestingacademy.com, the community included, slowly, so that you see a single website soon.

Task. Build a test duration report class: it takes each test's name and time, and gives the total time and the slowest test. The TA is to give it to everyone, with proper instructions.

How do you test a feature that depends on dates and time zones?

Worth practising too: How many constructors can a JavaScript class have, and what happens with two? Can a JavaScript constructor carry the class's name, as in Java, or be private? Where must a private # field be declared, and who can use it? What does this refer to in a constructor? What does a constructor bring to a Playwright class? What is the difference between a static member and an instance member, and why does TestRunner.pramod_fn() fail?

Show the answer

Answer. It is an interview question, the instructor said, and a room of Tester Town asked it. Answers came in: by changing the times and everything, by timestamps, by changing the times locally, by controlling the clock instead of using the real time. So we can control the clock or change the daylight saving time, the instructor said, and we can change the time zones and locales on the Mac too. A JavaScript class has one constructor at most, named constructor: a second is SyntaxError: A class may only have one constructor. A method named after the class is only a method, so nothing sets up the object, and #constructor is SyntaxError: Class constructor may not be a private method; a private constructor would leave no way to create an object anyway. A # field must be declared in the class body, and only code inside the class can use it: cred.#apiKey outside is a SyntaxError, while the public cred.user prints. In a constructor, this is the current object reference: the object being made. A constructor assigns the starting values whenever an object is created, so every object starts with something, not zero. A static member belongs to the class and is shared, read as TestRunner.totalTests; an instance member belongs to each object, as t1.name. pramod_fn() has no static, so it belongs to the objects: TestRunner.pramod_fn() is a TypeError, and t1.pramod_fn() works.