Internals of JavaScript — Classes and Objects
2 min readMar 16, 2021
let assert = require ('assert');class Book {
// constructor becomes part of the function object
constructor(/* this = reference of newly created object */ title, author, price){
// create new data members in the object and initialize them
this.title = title; // create title as the property in the object referred by this
this.author = author; // create author as the property in the object referred by this
this.price = price; // create price as the property in the object referred by this
}// display becomes part of the prototype object
display(/* this = reference of calling object */){
console.log(this.title, this.author, this.price);
}
}// Books refers to function object
assert.equal(typeof Book, "function");// Book refers to the function object
// and the function object contain prototype property
assert.notEqual(Book.prototype, undefined);// Book function / class inherits Object class
assert.equal(Book.prototype.__proto__, Object.prototype);let b1 = new Book("T1", "A1", 1000);
// 1. new Book object will be created with __proto__ in it
// 2. constructor will be called with reference of the object, T1, A1, 1000
// 3. new returns reference of the object which gets stored in b1// object to which b1 refers has been created from the Book class
assert.equal(b1.__proto__, Book.prototype);assert.equal (b1.title, "T1");
assert.equal (b1.author, "A1");
assert.equal (b1.price, 1000);let b2 = new Book("T2", "A2", 2000);
// 1. new Book object will be created with __proto__ in it
// 2. constructor will be called with ref of the object, T2, A2, 2000
// 3. new returns ref of the object which gets stored in b2// object to which b1 refers has been created from the Book class
assert.equal(b2.__proto__, Book.prototype);assert.equal (b2.title, "T2");
assert.equal (b2.author, "A2");
assert.equal (b2.price, 2000);// Is display() part of the Book's prototype object
assert.notEqual(Book.prototype.display, undefined)// pass reference stored in b1 to this
b1.display();// pass reference stored in b1 to this
Book.prototype.display.call(b1);assert.notEqual(b1.display, undefined)// pass reference stored in b2 to this
b2.display();// pass reference stored in b2 to this
Book.prototype.display.call(b2);