Category Archives: javascript

this context, change it via call, bind

Non Strict

In non-strict mode AND in standard JS environment, ‘this’ is an empty literal object.

Within a standalone function, global object is called global.

The

The only difference is that the ‘this’ in functions, is tied to global. In strict mode,
the ‘this’ in functions is undefined and not attached to anything.

Strict mode

In strict mode, the global object is called global. And ‘this’ is an empty literal object.
However, when you are inside a standalone function, the ‘this’ is undefined and not attached.

or…

Adding properties to global variable

all functions inherit call and apply from Function.prototype

Passing literals instead of objects

If the value passed as this is not an object, an attempt will be made to convert it to an object using the internal ToObject operation.

So if the value passed is a primitive like 7 or ‘foo’, it will be converted to an Object using the related constructor, so the primitive number 7 is converted to an object as if by new Number(7) and the string ‘foo’ to an object as if by new String(‘foo’), e.g.

Bind

Arrow functions

The idea is that arrow functions, when first created, set its this to its enclosing lexical context.
In other words, it retains the value of the this of its enclosing scope.

Let’s try to manipulate it and see if we can change it.

We try to do this by creating a literal object. Then use various ways to bind that object to our foo function’s this.

1) Object calls function

In the literal object, we create a property and have its reference pointing to the arrow function.
Then we simply execute the arrow function via the object’s property like so:


output:
inside arrow function:
{}

As you can see, the “this” in the arrow function does not reference its calling object ‘obj’. It references ‘this’ in its enclosing context.

2) Next, let’s try to bind the “this” in the arrow function to its calling object via call.
We get the reference to the arrow function and execute “call” on it. We would think we can bind the obj in the parameter to foo’s this. However, that is not the case. The ‘this’ in the arrow function is still bound to its enclosing lexical context.

3) This time, we’ll try using bind. We get the reference to the arrow function “foo”, call bind on it, and provide “obj” as the “this”. However, when we call foo, it does not work. It till uses its enclosing lexical context’s “this”.

Therefore, no matter what, foo’s “this”, it is set to what it was when it was created.
Their “this” remains that of the enclosing lexical context.

Returning an arrow function, and evaluating ‘this’

So the point of this example is to show the difference between calling

and

..as both have very different results.

First, let’s define the environment.

We have a literal object obj which has a public property bar. bar is a function that returns
an arrow function that logs “this”.

In the bar function, I also log “this”. That way we can compare.

First, we simply execute the bar function. Because the calling scope is obj, the “this” will belong to literal object “obj”.

Therefore, the logging of “this” will be:


√ bar’s this is:
{ bar: [Function: bar] }

We then execute what bar has returned, which is the arrow function. The output is:


— in arrow function —
{ bar: [Function: bar] }

This is because since the “this” in bar references the literal object “obj”, the arrow function’s this references the enclosing context, which is also “obj”.

In the next example, its the same concept, except we just separate the execution of bar and the arrow function.

Finally, we simply reference the function provided by obj. It does not take into account
of obj. fn2 simply is a reference to the standalone function bar. Whereas before,
variable fn referenced an literal object’s execution of its function.

Thus, if you were call it as a standalone function, your calling scope is global.
Before, in the previous example, the calling scope is the literal object.

For arrow functions, the “this” will always be what it was set to initially.

As an Object Method

this with a getter or setter

ref – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
ref – http://chineseruleof8.com/code/index.php/2018/01/15/getter-setter-js/

Data types, variables for JS

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures

Quick Tip: How to Declare Variables in JavaScript

Data types
The latest ECMAScript standard defines seven data types:

Six data types that are primitives

Boolean
Null
Undefined
Number
String
Symbol (new in ECMAScript 6)
and Object

All types (except objects) define immutable values (values, which are incapable of being changed). For example and unlike to C, Strings are immutable. We refer to values of these types as “primitive values”.

Integer type
Size: 8 bytes (2 ^ 64 bits allowed values)
Allowed values: 18437736874454810624 finite numbers (half positive half negative, including positive and negative zero) and three symbolic values NaN, Positive Infinity & Negative Infinity

Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).

A decimal integer literal consists of a sequence of digits without a leading 0 (zero).
A leading 0 (zero) on an integer literal, or a leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7.
A leading 0x (or 0X) indicates a hexadecimal integer literal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F. (The case of a character does not change it’s value, e.g. 0xa = 0xA = 10 and 0xf = 0xF = 15.)
A leading 0b (or 0B) indicates a binary integer literal. Binary integers can only include the digits 0 and 1.

Some examples of integer literals are:

0, 117 and -345 (decimal, base 10)
015, 0001 and -0o77 (octal, base 8)
0x1123, 0x00111 and -0xF1A7 (hexadecimal, “hex” or base 16)
0b11, 0b0011 and -0b11 (binary, base 2)

Boolean type
Boolean represents a logical entity and can have two values: true, and false.

The Boolean type has two literal values: true and false.

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type.

If we evaluate “undefined” or “null”, it is false.
If we pass them into a Boolean object, it evaluates to true. This also applies for ‘false’.

For example, the condition in the following if statement evaluates to true:

This behavior does not apply to Boolean primitives. For example, the condition in the following if statement evaluates to false:

Do not use a Boolean object to convert a non-boolean value to a boolean value. Instead, use Boolean as a function to perform this task:

If you specify any object, including a Boolean object whose value is false, as the initial value of a Boolean object, the new Boolean object has a value of true. That’s because an Boolean Object instance does not return primitive true or false. It returns an object and will evaluate to true.

Do not use a Boolean object in place of a Boolean primitive.


output:

its true! 😀
bool is true
bool2 is true
bool4 is true

Null type
The Null type has exactly one value: null. See null and Null for more details.

Undefined type
A variable that has not been assigned a value has the value undefined. See undefined and Undefined for more details.

String types

JavaScript is case-sensitive and uses the Unicode character set.

JavaScript’s String type is used to represent textual data. It is a set of “elements” of 16-bit unsigned integer values.
There are 2^16 (or 0-65535), 0xFFFF representations of text. The encoding is UTF-16, So 0-65535 text representations are mapped from UTF-16. You can view the table at https://upload.wikimedia.org/wikipedia/commons/0/01/Unifont_Full_Map.png
Top is 0 to FF. Left side is 0 to FF. Thus, 0xFFFF is 0-65535.

ref – http://chineseruleof8.com/code/index.php/2017/06/07/unicode/

JavaScript strings are immutable (unchangeable), once a string is created it is impossible to modify it. However, it is still possible to create another string based on the original by using string functions such as substr and concat.

An empty string has length zero and therefore contains no elements.

String literal

“string here” + “haha” + etc.

ES6 template literals, as the name suggests, come with a new literal syntax. They use back ticks ( ) to denote the start and end (just like strings use quote marks (‘ ‘ or ” “)). Within those back ticks, Template literals are parsed at runtime, to provide some new features.

A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal, or a leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7. A leading 0x (or 0X) indicates a hexadecimal integer literal.

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ( [] ). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified

The following example creates the coffees array with three elements and a length of three:

If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.

Extra commas in array literals
You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with undefined for the unspecified elements. The following example creates the fish array:

This array has two elements with values and one empty element (fish[0] is “Lion”, fish[1] is undefined, and fish[2] is “Angel”).

If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no myList[3]. All other commas in the list indicate a new element.

Note : Trailing commas can create errors in older browser versions and it is a best practice to remove them.

In the following example, the length of the array is four, and myList[0] and myList[2] are missing.

In the following example, the length of the array is four, and myList[1] and myList[3] are missing. Only the last comma is ignored.

Object Literal

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.

console.log(unusualPropertyNames.”); // SyntaxError: Unexpected string
console.log(unusualPropertyNames[”]); // An empty string
console.log(unusualPropertyNames.!); // SyntaxError: Unexpected token !
console.log(unusualPropertyNames[‘!’]); // Bang!

Variables

Declaration: The variable is registered using a given name within the corresponding scope (explained below – e.g. inside a function).

Initialization: When you declare a variable it is automatically initialized, which means memory is allocated for the variable by the JavaScript engine.

Assignment: This is when a specific value is assigned to the variable.

Declaration Types
Note: while varhas been available in JavaScript since its initial releast, letand const are only available in ES6 (ES2015) and up.

This declaration is probably the most popular, as there was no alternative until ECMAScript 6. Variables declared with var are available in the scope of the enclosing function.

Example:

If there is no enclosing function, they are available globally.’

// https://stackoverflow.com/questions/36797206/what-is-the-symbol-primitive-data-type-in-javascript?noredirect=1&lq=1

They prevent using a simple string to reference the field, so only consumers with the symbol can gain access.
So consumers can’t just create a string and access stuff from the object.

In general, symbols are intended as a replacement for magical names. Rather than having a properties simply called ‘foo’, you can allocate a symbol const foo = Symbol() and pass that selectively.

Symbol Type

How they are stored

Why do we use a temporary box in prototype inheritance?

https://stackoverflow.com/questions/47843315/why-do-we-use-a-temporary-box-in-prototype-inheritance

The function below is one that Derek Banas on youtube on his OO Javascript tutorial uses.

You have a function A that you want as a child. You have function B that you want as a parent.
You want to connect them using a function called extend.

The implementation is:

but why is this so?

Prototype objects are single literal objects. We need to create a Temp function that points to the Parent prototype object first, then spawn a instance, which acts as a single literal object.

This single instance will act as the Child’s Prototype Object, which is connected to Parent’s Prototype object.

1) Creating a custom Child Prototype object.

It should be done by like so:

which will give you an empty object with its __proto__ pointing to Foo’s prototype object. However, since we’re gunna do it by hand, we’ll do it step by step.

Setting up Child Prototype Object

First, we create the function Parent. By default, it will have a literal object called Parent Prototype. This Parent Prototype will have __proto__ pointing to default Object Prototype.

– Parent will have a ‘prototype’ reference to Parent Prototype
– Parent Prototype will have a ‘constructor’ reference to Parent

In order to create a Child Prototype Object, we first must create a function Temp to estabblish a Temp setup. The Temp will have a prototype reference to a Temp Prototype object. The Temp Prototype will have a constructor reference back to the temp. And by default, the Temp Prototype will have a __proto__ to the default Object Prototype, as shown in the diagram.

Then, with this setup, if we create an instance of Temp, that instance of Temp, will have its __proto__ pointing to Parent Prototype. We then call this new Temp object “Child Prototype Object”

From here, when we instantiate a child object, it will have its __proto__ pointing to Child Prototype Object. We can access any functions declared there. If it doesn’t exist, it will go up the hierarchy tree via __proto__, which is Parent Prototype. If it does not find it there, it goes up the next __proto__, which is the Object Prototype. And if its not there, then what we’re looking for does not exist.

Object.create

ref – https://stackoverflow.com/questions/62378057/what-is-the-difference-between-object-assignment-and-object-create

Object.create(param) creates an empty object, with its __proto__ pointing to “param”. That way, the empty object can inherit properties from param.

We’ll demo this by first creating a literal object with “person” variable referencing it.

Now, in JS, the base Object class is an object that has a prototype reference that points to an Prototype Object. Its Prototype Object then has a constructor reference pointing back to the Object class.

Every object created in Javascript, will have its reference __proto__ pointing to Object’s Prototype Object. This situation is shown in the diagram:

Notice Object’s Prototype Object has a __proto__ pointing to null. __proto__ is the reference that indicates which object you inherit from. Thus, since our base class Object is the parent class of every object, it does not inherit from anyone. Thus, its Prototype Object’s __proto__ will be null.

Our person object will have its __proto__ pointing to the Object’s Prototype Object. This means our object derives from Object.

Create empty object and inherit from person object

We create an empty object called me, that extends from the person object we just created.
We do this like so:

1) Object.create will create an empty object
2) It will then point the empty object’s __proto__ reference to our person object

For completion purposes, let’s just add property “name” and initialize it to “Matthew”.

Now, using the me object, we can access its inherited properties from the person object. The reason why we can call printIntroduction is because me’s __proto__ points to person. It is set automatically by Object.create.

Let’s check out what the me object looks like.

We’ve accessed the function printIntroduction through me. Now let’s access the property isHuman.

Extending an Object

Previously, we’ve extend a literal object. Now, let’s extend a function object so that when we instantiate it by using new, all the instantiations will have the same inheritance.

First, let’s create a function called CoolPerson.

Basically, CoolPerson is a function object. This function object has a prototype reference to another Object (CoolPerson Prototype Object) that houses all a lot of properties and functions. It includes the constructor, which points back to function CoolPerson, and also a __proto__ that points to Object’s prototype object.

Let’s verify by logging CoolPerson, and its references.

console.log(CoolPerson) // [Function: CoolPerson] or f CoolPerson

Check out the output to make sure everything checks through.

Re-point prototype, creating a constructor and pointing it to the correct function

Previously, from above, we created a person object. It is a literal object that derives from base Object’s prototype.

When you try to access ‘constructor’, it will first see that person itself does not have a constructor property. We use hasOwnProperty to do this. However, when we do access the constructor, we see that it points to the default Object. This is because person uses its inheritance via __proto__ and finds that inheriting from Object’s Prototype Object, it does have a constructor property. This constructor property points to native Object.


> person
{isHuman: false, printIntroduction: ƒ}
> person.hasOwnProperty(constructor)
false
> person.constructor
ƒ Object() { [native code] }

1) Thus, first we need to repoint our prototype to person. What this means is that any instantiations created with “new” will inherit from peron.
2) we then need to create a property called constructor and attach it to person. This is so that the instantiations of CoolPerson will display their correct type. If you don’t do this, the instantiations will have type “Object”, instead of type “CoolPerson”.

Now, we can instantiate c. We are able to use property name from its original definition, and also access inherited properties from person object, such as isHuman, and printIntroduction.

Instantiation using inherited functionalities

The diagram for function CoolPerson that inherits from person object looks like this:

You’ll notice that an instance of CoolPerson will always inherit from the person object via its __proto__ reference. When a function definition in the person object accesses the ‘this’, the ‘this’ refers to the instance itself.

When instance c was made from function CoolPerson, it copies all the properties, including ‘name’. Thus, instance c has its own name. Once it access the singleton person object and sees this.name, it knows that this refers to the instance itself. And looks to see if there is a name property in the instance. It does, and hence it will use the name property in the instance.

Another Example

Connecting Hierarchy

Say we want to extend Person.
1) Create Student function object
2) const protoObj = Object.create(Person.prototype) // this creates an object with proto pointing to Person.prototype
3) Student.prototype = protoObj
4) protoObj.constructor = Student

So now when you create an instance say

OOP in Javascript (with Node)

ref – http://book.mixu.net/node/ch6.html

The new constructor call (e.g. new Foo()):
creates a new object,
sets the prototype of that object to Foo.prototype and
passes that as this to the constructor.

The prototype chain lookup mechanism is the essence of prototypal inheritance.

Instantiate the class:

Adding private variables

Avoid assigning variables to prototypes

If you want to define a default value for a property of an instance, define it in the constructor function.

Prototypes should not have properties that are not functions, because prototype properties that are not primitives (such as arrays and objects) will not behave as one would expect, since they will use the instance that is looked up from the prototype. Example for Dimitry Sosnikov’s site:

Hence prototypes should only define methods, not data.

static vs non-static

ref – https://stackoverflow.com/questions/45594196/difference-between-static-function-declaration-and-the-normal-function-declarati

That’s the very definition of a static function that you don’t have to instantiate the class to call it. That’s not something JS specific.

A static method is callable from the class itself

A non-static method is callable from an instance of the class, so you basically have to create an object before being able to access that method.

Although in the end, both is just little more than:

es6 classes just make it look nicer. Syntactical sugar.

For example, for a addNumbers(var a, var b) which does return a+b, is it really necessary to waste memory instantiating an object of the class just to add those 2 numbers? No, you just need the result and that’s the whole point of having static.

Using the first style allows you to group methods in a particular class (think of something like namespaces). Maybe you can define classes like Math and String, which both have the add method but implemented in a different way. Calling add() by itself would be confusing, but Math.add() and String.add() are not.

function expression vs declarations (js)

ref – https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

Quick Tip: Function Expressions vs Function Declarations

What is a Function Declaration?

A Function Declaration defines a named function variable without requiring variable assignment.

Function Declarations occur as standalone constructs and cannot be nested within non-function blocks.

It’s helpful to think of them as siblings of Variable Declarations. Just as Variable Declarations must start with “var”, Function Declarations must begin with “function”.

a function declaration:

ECMA 5 (13.0) defines the syntax as
function Identifier ( FormalParameterListopt ) { FunctionBody }

Similar to the var statement, function declarations are hoisted to the top of other code.

What is a Function Expression?

A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment ). Functions defined via Functions Expressions can be named or anonymous.

Function Expressions must not start with “function”
Rather, they start with a var reference, or a parentheses.

more examples:

Function expressions aren’t hoisted, which allows them to retain a copy of the local variables from the scope where they were defined.

Benefits of Function Expressions
There are several different ways that function expressions become more useful than function declarations.

As Closures

Closures are used when you want to give parameters to a function, before that function is executed. A good example of how this can benefit you is when looping though a NodeList. A closure allows you to retain other information such as the index, in situations where that information will no longer be available when the function is executed.

Let’s create a unordered list with class “tab”:

Then we loop over the elements, and assign it a click event like so:

Note that, tabs[i] is an HTML Element object. It has an “onclick” callback handler.
We need to provide it a function so that the HTML element tabs[i] has a callback function to execute after running its own code.

the HTML element tabs[i] will also pass event object (filled with info on the click itself)
thus, when we click, it’ll call our “standardFunction”
and also we get to analyze (and use) an event object.

In terms of scope, you can access parent’s scope variable i. However, note that the loop runs first, going from 0 to 2, and assigning all callback functions first in the process. After it finishes assigning the function, the i is at 2.

When you click, the callback will execute and since our scope is parent, it will access i, which is 2.

This isn’t what we want. We want to keep track of the index.

Solution

The solution to keeping track of this index is to use a closure. Closures are objects and depending on implementation (gets moved around from stack to heap). Its a way to reference scope and variables. In our case, we first create a function called rickysHandler where we pass in the index i.

rickysHandler’s has a inner function called tabClickEvent, which is returned to a tab’s onclick.
Whenever a click happens, it will execute this tabclickEvent.

rickysHandler takes the index and creates a closure for tabClickEvent. Under the hood, whenever tabs[i].onclick gets assigned to a rickysHandler(i), it creates a closure where i lives. And then the function tabClickEvent references it.

so tabs[0].onclick references its own function tabClickEvent, where it reference a closure with index 0
so tabs[1].onclick references its own function tabClickEvent, where it reference a closure with index 1
so tabs[2].onclick references its own function tabClickEvent, where it reference a closure with index 2

like so:

Passing as Arguments

Function expressions can be passed directly to functions without having to be assigned to an intermediate temporary variable.
The Array prototype has a forEach function can use to iterate through all the elements. The forEach function takes a function expression. We create an anonymous function expression and pass it in.

As Immediately Invoked Function Expressions (IIFE)

IIFE’s are used to help prevent your functions and variables from affecting the global scope. All the properties within are scoped to the anonymous function. This is a common design pattern that’s used to prevent your code from having unwanted or undesired side-effects elsewhere.

It’s also used as a module pattern to contain blocks of code in to easy to maintain sections.

classes (js)

  • https://reinteractive.com/posts/235-es6-classes-and-javascript-prototypes
  • https://levelup.gitconnected.com/using-classes-in-javascript-e677d248bb6e?gi=5ba413dea026

Why do we need classes?

Classes are simply templates used to create new objects. The most important thing to remember: Classes are just normal JavaScript functions and could be completely replicated without using the class syntax. It is special syntactic sugar added in ES6 to make it easier to declare and inherit complex objects.

We create a class like so:

We declare scoped variable in constructor for privacy.

So, a class like this:

translates to this:

Constructor

There can be only one special method with the name “constructor” in a class. Having more than one occurrence of a constructor method in a class will throw a SyntaxError error.

A constructor can use the super keyword to call the constructor of a parent class.

If you do not specify a constructor method, a default constructor is used.

Then we implement getter/setter functions for it and attach them to the this object.
Whenever we attach functionality and property to this, its public.

We can then declare other functions that use private properties such as _name.

For example, if we want to implement private removeLastNode that accesses these private properties/functions, we do so in the constructor because removeLastNode can access _name, _head, _tail by scope. removeLastNode is not visible to the outside.

public functions that uses private properties/functionalities

Now, say we want to implement remove function that wants to access our private function and private properties, we simply implement the public function inside of the constructor, and access those private functionality and properties via scoping.

Notice our remove function is public because it is attached to this.
It accesses private properties such as _head due to scoping.
It accesses private functions such as removeNodeAtHead(…) due to scoping.

functions

functions are attached to the this object, and are public.
If the functions want to use use private properties, they must be in the same scope as the private properties/functionalities, which are in the constructor as shown previously.

In this case, if the functions are outside of the constructor, they use private variables through get/set functions that are exposed on the this object.

functions attached to this are added to the prototype

Take this example, class Test.

Any functions/properties added to Test.prototype is shared among all instances.
Any functions/properties added outside of the constructor function is added to Test.prototype and is hared among all instances.
Any functions/properties added inside of the constructor belongs to the instance itself.

you can check like so:

you can also simply input the code into Firebug and then simply log a.__proto__

you will see that the prototype object will have haha, print, and constructor.
The object itself will have print2.

Thus the methods is being shared by all instances of Test.
Adding methods on the prototypes of objects in JavaScript is an efficient way
to conserve memory (as opposed to copying the methods on each object).

Hi-Jacking these functions on the fly

Prototypes are just objects that can be changed at runtime

Changing the method on the prototype of ‘a’ changes the result on ‘b’ as well.

This is because they share the same prototype and we are changing that object.

Again, prototypes are just objects that can be changed at runtime.

Oops, there is no going back, we have already modified the prototype for all instances of CircularList, now and in the future.

Remember, classes in JavaScript are not a blueprint like in other languages.
They just define objects that can be modified at will in runtime.

TO RECAP:

Inheritance

Continuing from our Test class example…

And OralText to extend from Text:

this is what it looks like diagram form:

So we start off with class Test. We declare function print2 inside the constructor, so its a property of the class. Every instance created from this class will have its own print2.

We then declare function print within the class, but outside of the constructor. print will be included in Test’s prototype object, which is simply represented as {}. This is because it derives (has __proto__ referencing) the default Object Prototype Object. There is no class name it derives from so its empty. Then, we directly attach the function haha to Test’s prototype object. Also, constructor is the special function that all instances of this class need to call before instantiation. Thus, that is why Test Prototype Object has haha, print, and constructor.


> Test.prototype

{haha: ƒ, constructor: ƒ, print: ƒ}
haha: ƒ ()
constructor: class Test
print ƒ print()
__proto__:Object

Then we have OralText, which extends from Test. It copies over the constructor properties, hence we get print2.

More importantly, this Test{} is independent from Test’s prototype object. OralText.prototype has a constructor property, which points back to OralTest. Thus, all instances created from OralTest will have OralTest as its type.

Another important thing is that OralTest.prototype is an object instantiated from Test.prototype. That’s why it has a __proto__ pointing to Test.prototype. This is so that we have a hierarchy in case instances of OralTest wants to access its parent’s prototype.


> OralTest.prototype

Test {constructor: ƒ}
constructor: class OralTest
__proto__: Object

As you can see OralTest’s prototype has a constructor pointing to OralTest (itself). This is so that all instances of OralTest will have OralTest as the type.
We also wee that the name of our prototype object is called Test This is because we extend from Test. Its __proto__ is referencing an Object. Let’s analyze this Object:


OralTest.prototype.__proto__

{haha: ƒ, constructor: ƒ, print: ƒ}
haha: ƒ ()
constructor: class Test
print: ƒ print()
__proto__: Object

So as we see, its the Test’s Prototype object with the haha and print functions.

So now
OralFinal.prototype will give a literal object with the name OralTest. Because our OralFinal extends from OralTest. You’ll see the special constructor function.

We are now at the lowest level of the hierarchy. We want to go up the hierarchy. So we follow the __proto__ path. You’ll see its __proto__ is that of Test. This is because OralFinal’s Prototype Object OralTest, is an object instantiated from Test.

OralTest {constructor: ƒ}
constructor :class OralFinal
__proto__: Test

If you go up one more __proto__, aka __proto__ of Test, you’ll see the no name Prototype Object with the functions haha, print, constructor.

Then if you go up one more, you’ll reach the default object Prototype object. That is the highest point.

  • Classes are NOT hoisted
  • Classes are first-class citizens
  • Classes are executed in strict mode

Another Example

Given class PersonCl:

Private properties in es6 classes (js)

references:

  • https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes
  • https://www.javascriptjanuary.com/blog/es6-classes
  • https://ttmm.io/tech/private-variables-in-javascript/
  • https://esdiscuss.org/topic/es6-problem-with-private-name-objects-syntax

ECMAScript 2015 (aka ES6) introduced classes to JavaScript.

Older versions of the language would allow you to define an object type directly using function constructors, but didn’t truly support object-oriented inheritance the way developers are used to.

Part of this is due to the fact that JavaScript is a prototypal language, not an object-oriented language. Or at least older versions weren’t.

ES6 gave us classes with proper constructors, methods, properties, and inheritance.

You could define a real class in ES6 and reuse it the same way you would a type in any other language:

The biggest unfortunate element of this class definition, though, is that there are no privacy modifiers.

The constructor, methods, and properties of a JS class are all public by default.

There’s no nature of a protected method or a private property. At all.

Module Privacy

The name variable inside this module is completely inaccessible to any code outside the module, yet it allows our class to keep track of this name property directly. This is exactly what we want, right?

Nope.

Since it’s outside the class definition, this variable is treated as a static property. Yes, it’s private to our module, but there’s only one copy available. If we make multiple instances of our Client above, we’ll overwrite name each time; the last instantiation will win and define the name used by all of the instances.

Hack

We create a static literal object called container. When an instance of Client is created, we give the instance an id, then use the instance id
to create a key in the container object. Its corresponding value would be an empty object where we store the name variable.

Thus, each instance at least can keep track of its own properties and usage.

Not attaching the new properties to the object, but keeping them inside a class constructor

Hiding with Weak Maps

https://javascript.info/map-set-weakmap-weakset
https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes

WeakMaps associate data with Objects (here, instances) in such a way that it can only be accessed using that WeakMap. So, we use the scoped variables method to create a private WeakMap, then use that WeakMap to retrieve private data associated with this. This is faster than the scoped variables method because all your instances can share a single WeakMap, so you don’t need to recreate methods just to make them access their own WeakMaps.

WeakMap, another way

https://chrisrng.svbtle.com/using-weakmap-for-private-properties

WeakMap Technique
Traditionally, the way to have private properties in Javascript is to either prefix your variables or to encapsulate in a closure. Both of these methods do work, however they are either not restrictive enough (prefixes) or too restrictive (closures).

A WeakMap is similar to a HashMap but it allows objects as keys as well as not having a strong reference to its values (that’s why it’s called weak).

In the example below, we pass in an empty object into the WeakMap to hold all of the private properties of the class Wizard. To store the private properties, we also pass in the reference to the unique this object of the instance of the class Wizard as a key to the WeakMap.

When we actually run this code, you can see on the second line that when we try to access the property _private the class returned does not have reference to it because of the IIFE. However internal class methods can still change the values under _private. So you can only change the properties within the Class by using its accessor methods such as get and set. In doing so, keeping the namespace hidden from all functions except members of the class effectively implements private properties.

Break Down

ref – https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes

The only truly private data in JavaScript is still scoped variables. You can’t have private properties in the sense of properties accessed internally the same way as public properties, but you can use scoped variables to store private data.

Scoped variables

The approach here is to use the scope of the constructor function, which is private, to store private data.

For methods to have access to this private data they must be created within the constructor as well, meaning you’re recreating them with every instance.

This is a performance and memory penalty, but some believe the penalty is acceptable. The penalty can be avoided for methods that do not need access to private data by adding them to the prototype as usual.

Example:

Scoped WeakMap

A WeakMap can be used to avoid the previous approach’s performance and memory penalty.

WeakMaps associate data with Objects (here, instances) in such a way that it can only be accessed using that WeakMap. So, we use the scoped variables method to create a private WeakMap, then use that WeakMap to retrieve private data associated with this. This is faster than the scoped variables method because all your instances can share a single WeakMap, so you don’t need to recreate methods just to make them access their own WeakMaps.

Example:

This example uses an Object to use one WeakMap for multiple private properties; you could also use multiple WeakMaps and use them like age.set(this, 20), or write a small wrapper and use it another way, like privateProps.set(this, ‘age’, 0).

The privacy of this approach could theoretically be breached by tampering with the global WeakMap object

Say you’re coding up a JS app and you import another file written by Fred for usage.
Then in your current file, you create your class and then use WeakMap to store your private variables.

index.js


output:
I am Private1 I am Private2

However, say Fred is a bit naughty and decide to overwrite the global object Weakmap like so:

base64Coder.js

So Fred decides to repoint the set reference in Weakmap’s prototype to his own custom function. But before doing so, in order not to lose the original function, he’ll retain it with a reference called oldSet.

He then has access to your key/values and can potentially change them, or even store them somewhere else. When he’s done, he’ll just return the original function, pointed to by referenceoldSet.

That said, all JavaScript can be broken by mangled globals. Our code is already built on the assumption that this isn’t happening.

Solution to fix this

In order to remedy this, you first declare references to the original set/get functions on the Weakmap prototype.
This ensures you have access to them. Now, when the tamperer decides to inject their own function, what they’re doing is re-pointing Weakmap.prototype.set to their own evil function as shown above. Thus, you don’t have to worry about that because you have already set your own reference to the correct original functions like so:

The way how it used is like so. The first object is the object you’re using to execute the function call. The next parameters get matched up with the function parmaeters.

Just make sure you do it at the top of your file before you import/require the questioning code components.

Half Answer – Scoped Symbols

A Symbol is a type of primitive value that can serve as a property name. You can use the scoped variable method to create a private Symbol, then store private data at this[mySymbol].

The privacy of this method can be breached using Object.getOwnPropertySymbols, but is somewhat awkward to do.

Example:

For example, this is how you would expose it:

Half-Answer: Underscores

The old default, just use a public property with an underscore prefix. Though not a private property in any way, this convention is prevalent enough that it does a good job communicating that readers should treat the property as private, which often gets the job done. In exchange for this lapse, we get an approach that’s easier to read, easier to type, and faster.

Example:

Decoupling JS apps using publisher subscriber pattern

http://dev.housetrip.com/2014/09/15/decoupling-javascript-apps-using-pub-sub-pattern/
https://gist.github.com/fatihacet/1290216

The problem

Let me use one of the most common features in modern web applications to introduce the problem: sending notification emails.

Let’s say we’re building an e-commerce site and we’d like to send a notification email to the customer when they make a purchase. A simple solution, and probably the most common one, could be something like this:

Notice how in sendEmail definition, it creates an instance of Mailer and calls function “sendPurchaseEmail”.
These two objects now have tight coupling because if you were to change sendPurchaseEmail to another name, you’ll have to do the same for sendEmail in Order. In other words, if you were to change the # of parameters, or the interface of the sendPurchaseEmail function, you’ll have to repeat those steps for sendEmail in Order.

Usually you know two components are coupled when a change to one requires a change in the other one, and that’s the case. If we want to change the name of the sendPurchaseEmail method or their params, we’ll have to change Order implementation as well. In a large application this bad practice means having a tightly coupled application where a small change can easily end up in a waterfall of changes.

What we want is Loose Coupling. Loose coupling is when you change the interface, but do not have to worry about changing it in all the other places that you have used it.

What is the Publish Subscribe Pattern?

In software architecture, publish–subscribe is a messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers. Instead, published messages are characterized into classes, without knowledge of what, if any, subscribers there may be. Similarly, subscribers express interest in one or more classes, and only receive messages that are of interest, without knowledge of what, if any, publishers there are.

This pattern uses an event system that sits between the objects wishing to receive notifications (subscribers) and the objects firing the events (the publishers). This event system allows code to define application specific events which can pass arguments containing values needed by the subscriber. The goal is to avoid dependencies between the subscriber and the publisher.

Implementation

First, we declare a global literal object. This object takes will have the functionalities of publishing and subscribing.

It will be passed into an IIFE so that it has private block scope for its data structures.

then we create the data structures and variables needed for the implementation.

Say there’s a couple of topics: Badminton, Boxing, and Swimming.
First, we use the concept of key: value in order to keep track of them.
The key is the activity name “Badminton”, “Boxing”, “Swimming”.
We have a topics literal object that will store these keys.

TOPICS:

{
“Badminton” : [subscriber1, subscriber2, subscriber3….subscriber n]
“Boxing” : [{token: abcdefg, func : callback}… {token: 38fje8, func : callback}],
“Swimming” : [{token: a1b2c3d4, func : callback}… {token: 0fjdue7, func : callback}],

etc
}

Then for each key, we will have a literal object as the value.

That literal object has 2 properties:
– token
– func

token is simply an uid
func is the callback provided by the subscribers. Essentially, whenever something happens
and we want to publish something, we call this func, then pass in some data if needed.

“Badminton” : {token: a4456iol, func : callback}

Hence for each topic, we have an array of objects. Each of these objects have token and func properties. These objects represent
external objects that has subscribed to us and want to receive notifications when something happens.

Subscribe

Therefore, we create a public function property called subscribe. Its first parameter is topic, which is the topic that the external object
wants to subscribe to. For example, badminton, swimming…etc. The func, is the callback that we can use to notify that external object.

We must check to see if the topic exist. If there’s only data for say Badminton, and we subscribe to “swimming”, our pubsub system
will create an key/value entry for swimming and then create an empty array. This readies future external objects that wants to
subscribe to the topic “swimming”.

Then, we simply use a increment to simulate id generator. It is assigned to the subscriber. That way, each subscriber has an unique id to identify itself.

Finally, we create an object to store the token and the callback for the subscriber. We store this object into the array that corresponds to the topic that the subscriber wanted.

When we publish, we call execute this callback so that its owner will receive it.

Publish

So we have all these subscribers stored for different topics and now we’re ready to publish!

We create a public property for the pubsub. The first parameter topic represents the topic we want to publish for.
args is any published data you want to pass to the objects stored in arrays of different topics (subscribers).

First we check to see if there are any subscribers for the topic at hand. If say we have 3 subscribers for “Badminton”, and we try to publish something for “swimming”, we just spit out an error message because no such topic exist.

{
“Badminton” : [subscriber1, subscriber2, subscriber3]
}

Then we use a setTimeout to simulate internet activity.
First we get the array of subscribers by accessing the value by using topic as the index.

In an associative array, giving the topic key will give us the object value (array of subscribers).

Then we simply get the length of the subscribers.

By using the length, we use it to access the array of subscribers by using index. Remember, using strings in an associative array
will give you the object value associated with it.

By using numeric index, you’ll simply be giving the object value by index.

Hence after getting the length, we simply go through the subscriber array by looping through its index from length to 0, and
calling each subscriber’s callback. We can pass in whatever data we like for the publish.

Using the pubsub object

Unsubscribe

First, we go through all the topics available in our topics associative array.
For each of these topics, there is a list of subscribers.

For each element of the array subscribers, we check to see if the subscriber has the token.
If so, we remove that subscriber from the subscribers’ array.

FULL SOURCE