0%

Javascript notes

Class

  • “Instantiating” a class in JavaScript does create a new object, but not one that is independent of its parent class. Rather, it creates an object that is linked to a prototype. Changes to that prototype propagate to the new object, even after instantiation.

  • Classes can only contain method definitions, not data properties;

  • A derived class can’t contain an empty constructor. Even if all the constructor does is call super(), you’ll still have to do so explicitly. It can, however, contain no constructor.

  • You must call super in the constructor of a derived class before you use this.

  • Calling any function with the new keyword causes it to return an object – this is called making a constructor call, and such functions are generally called constructors: When you call a function with new, four things happen under the hood:

    • A new object gets created (let’s call it O);
    • O gets linked to another object, called its prototype;
    • The function’s this value is set to refer to O;
    • The function implicitly returns O.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"use strict";

// Eliminating the need for 'new' -- just for demonstration
function Food (name, protein, carbs, fat) {
// Step One: Create a new Object
const obj = { };

// Step Two: Link prototypes -- we'll cover this in greater detail shortly
Object.setPrototypeOf(obj, Food.prototype);

// Step Three: Set 'this' to point to our new Object
// Since we can't reset `this` inside of a running execution context,
// we simulate Step Three by using 'obj' instead of 'this'
obj.name = name;
obj.protein = protein;
obj.carbs = carbs;
obj.fat = fat;

// Step Four: Return the newly created object
return obj;
}

Object and Object.prototype

  • all objects in JavaScript – including Functions – are linked to another object, called its prototype.

  • If you request a property on an object that the object doesn’t have, JavaScript checks the object’s prototype for that property.

  • Before the JavaScript engine executes a program, it builds an environment to run it in, in which it creates a function, called Object, and an associated object, called Object.prototype.

  • Object: The function, Object, is like any other function. In particular, it’s a constructor – calling it returns a new object.

  • The function, Object, has a property, called .prototype, which points to an object (Object.prototype);

  • The object, Object.prototype, has a property, called .constructor, which points to a function (Object).

  • As it turns out, this general scheme is true for all functions in JavaScript. When you create a function – someFunction – it will have a property, .prototype, that points to an object, called someFunction.prototype.

  • Conversely, that object – someFunction.prototype – will have a property, called .constructor, which points back to the function someFunction.

  • TBD

Reference