All posts by admin

Arrow functions (js)

ref – https://medium.com/@thejasonfile/es5-functions-vs-es6-fat-arrow-functions-864033baa1a
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
https://dmitripavlutin.com/when-not-to-use-arrow-functions-in-javascript/

When creating instances, every use of “new” defined its own ‘this’ value, where ‘this’ references the instance. The function defined in the constructor function will point to “this”. However, another function inside of that will not point to “this”.

Say we create a literal object and assign a reference named “Pets” to point to it.

The object has properties “names” and “owner”, and a description function. Let’s analyze how ‘this’ and the arrow functions affect each other.

In JavaScript, the method is a function stored in a property of an object. In our case, we have a function, and its stored in property “description”. When calling the method, “this” becomes the object that method “description” belongs to.

The “this” context in description is referencing the literal object that pets is pointing to. We see this when we log the ‘this’:


{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }

We see the object displayed in the console.

Inside of our description function, let’s say we create another function and have a reference called innerFunc pointing to it. We then execute the reference to the function to call it. You’ll see that the ‘this’ inside of innerFunc is undefined.

The reason why is because the inner function does not have a owner, whereas function description does. Inner function see its surrounding scope as function description, and does not detect an object. Hence innerFunc’s this is undefined.

In a more general sense, the solution is that we need to set innerFunc (and our callbacks) up so that it refers to the ‘pets’ literal object.

output:

— description —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ], owner: ‘Ricky’, description: [Function: description] }
— innerFunc —
undefined
— end of innerFunc —
— END OF description —

3 Workaround Solutions

Bind

We use the bind function to bind the pets this to our innerFunc.
Since our function innerFunc’s prototype is Object (as is with any compound objects in JS), we can use the bind function, and pass in the this. We do this inside of description function since description has the correct ‘this’ context.

Once bound, it returns a reference to the innerFunc with the correct this bound. We call that reference as a function and you’ll see that the “this” inside of innerFunc is valid.


— description —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— innerFunc —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— end of innerFunc —
— END OF description —

If you want multiple inner functions to work, you’ll have to repeat the binding of this object for each inner function.

Pass as a parameter

We can pass the this into the description function. Due to scope visibility, innerFunc will be able to see and use it.

Multiple inner functions will work also because the parameter is visible to them all.


— description —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— innerFunc —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— end of innerFunc —
— END OF description —

parent scope local var

Inside description function, we can push a reference called self onto the local stack, and have it point to the this object. Since self is at the parent scope of innerFunc, innerFunc sees self, and can use it.

Multiple inner functions will work because the scope of “self” is visible to them all.


output:

— description —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— innerFunc —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— end of innerFunc —
— END OF description —

Fat Arrow

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

An arrow function does not have its own “this”. The “this” value of the enclosing execution context is used. Thus, when using arrow functions inside of standard functions, the “this” within the arrow function will reference its enclosing function.

This works for multiple inner functions.

Arrow functions are best suited for non-method functions

..such as timer functions, array map functions, sync/async functions.
Any kind of functions used inside of calls should be used as arrow functions
because they can correctly find their outer scope’s this.

Arrow functions should not be used as method functions because for literal objects,
they cannot find the “this” to the literal object and will take the “global” this of
{} instead.

For example:

Arrow functions do not have their own this.

Arrow functions cannot be used as constructors and will throw an error when used with new.

Arrow functions do not have a prototype property.

Another Example

Another example is using globally defined functions like setInterval.
setInterval is a function defined in the global object Window and will be bound to that object.
Thus, whenever we call it, and try to use “this” in a function callback, the “this” will be referred to Window.
What we want is to make sure “this” refers to our Person object.

Thus, we have to use arrow function, because arrow function will get the “this” from its surrounding lexical scope.

Prototype and Inheritance in JS (non-class)

https://www.digitalocean.com/community/tutorials/understanding-prototypes-and-inheritance-in-javascript

note:

It is important to note that x.__proto__ is a legacy feature and should not be used in production code, and it is not present in every modern browser. However, we can use it throughout this article for demonstrative purposes.

Use Object.getPrototypeOf(x) instead.

Creating objects through Constructor Functions

Because each character will share many characteristics, such as having a name, and a level, we use a constructor functions to create templates for those common traits of each hero.

Every hero has a name, and a certain level of experience

We have created a constructor function called Hero with two parameters: name and level. Since every character will have a name and a level, it makes sense for each new character to have these properties.

The this keyword will refer to the new instance that is created, so setting this.name to the name parameter ensures the new object will have a name property set.

The hierarchy looks like this:

The Prototype Object

Whenever we create a constructor function, JS will automatically create a literal object that acts as the prototype object.

That literal object’s sole purpose is to contain functions and properties for all instantiations of your constructor functions.

Note that this object (like all objects of JS) derives from Object, and will have its __proto__ pointing to Object’s Prototype Object.

This literal object acts as the prototype object for Hero. It will also have a constructor property pointing back to your constructor function. Thus, making this prototype object the same type as your constructor function.

In our case, we create a constructor function “Hero” with its properties. JS gives us an empty literal object (Let’s call it Prototype Object) in order to act as a single object that keeps properties and functions that are shared among all instances of Hero.

Note that our Hero Prototype Object derives from Object and thus, has its __proto__ referencing Object‘s Prototype Object.

It then creates and assigns a “constructor” property from the Hero Prototype Object to your Hero constructor function. This makes the prototype object type Hero. Finally, it assigns the “prototype” property from your Hero constructor property onto the “Hero Prototype Object”.

Creating an Instance

What this means is that any instantiations of Hero will have its OWN properties and functions from the Constructor function.
hero1 is an instance we just created. It has its own properties of name and level, as indicated from the constructor function Hero.

hence if we were to make three hero objects, hero1, hero2, and hero3, they all have their own unique properties of name, and level.
i.e

hero1 is “Grom”, level 1
hero2 is “Haomarush”, level 2
hero3 is “Thrall”, level 8

In addition, they ALL share the “Hero Prototype object”.

So if the “Hero Prototype object” has a property “nickname” initiated to “Orc”, then they would all have nickname = “Orc”.

Same goes for any functions and other properties that “Hero Prototype Object” may have.

Let’s check on how this works. First we display the prototype of our object hero1. You can do it in 2 ways:


output:

Hero {}
Hero {}

Now repeat with hero2, hero3. You’ll see that their __proto__ all are Hero{}. They all point to the same Prototype Object Hero{}

Adding to the Prototype

Let’s add a property nickname to the prototoype, and see what it looks like:

Now our “Hero Prototype Object” will look like this:

Hero { nickname: ‘orc’ }

This means that when we try to read a property from a Hero object, say from hero1,
– it will try to look for “nickname” in the hero1 instance first.
– When it does not find it, it will go up the hierarchy (i.e hero1.__proto__) into the prototype object, which it will then find.
– If it still does not find it, it will keep going up the prototype chain, hero1.__proto__, hero1.__proto__.__proto__….etc

If you were to change nickname:

You cannot change it from the instantiation

Our hierarchy is like this.

We have our Hero instance, with its own properties of name and level. It has its __proto__ pointing to an object, with property “type”, which is
initialized to orc. It has its constructor back to Hero, and __proto__ references pointing to Object’s Prototype Object.

Simply put, don’t confuse yourself when you try to change a property or function of a prototype object.

You cannot change it through an instantiation like this:

Erroneously, many people may think that it will see if nickname exist in the instantiation, it does not. Then it goes up to the prototype and finds it there. Then it just assigns the new string.

When it comes to setting values, JS will only let you access at the prototype level. It only let’s you read at the object level if the property does not exist at the object level.

If you do decide to assign at the object level, essentially Javascript will interpret it as you wanting to add a property called “type” to your instance, and then initialize it.

Thus, in the hierarchy, you’ll get two property called “type”. One is at the instance level. One is at the prototype level.

If you want to set the prototype object to a new value, you must do so through Object.prototype.YourPropertyName.

Different character classes of heroes

However, each hero has different abilities. Some wield different weapons. All have vastly different skills and abilities.

It wouldn’t make sense to put all the abilities for every class into the Hero constructor, because different classes will have different abilities.

We want to create new constructor functions, but we also want them to be connected to the original Hero.

Let’s take a look at how we can accomplish this with prototype inheritance and constructors.

The Warrior

We use call in order to chain constructors. Essentially, call replaces a function’s this reference to a passed in object.
Hence, we replace Hero’s constructor function’s this reference to point to Warrior’s this. Then, any kind of initialization done in Hero will take place in Warrior. In other words:

  • We first create a constructor function called Warrior. This identifies Warrior.
  • We then pass the “this” reference to Hero via function call. Using Warrior’s “this” reference, we start to construct it like a Hero. Essentially, we are doing chain constructors for Warrior. We want to first initialize Warrior to be a Hero with Hero’s properties and functions.
  • Then, we come back to Warrior, and initialize Warrior’s properties.

note: The JavaScript call() Method

The call() method is a predefined JavaScript function method.

It can be used to invoke (call) a function with an owner object as the first argument (parameter).
In our example, instance person calls fullName. However, fullName’s this is myObject.

With call(), you can use a method belonging to another object.

This example calls the fullName function of person, but is using it on myObject:

…back to our example…

In the extended object Warrior, we initialize Warrior with Hero’s properties via javascript’s call function.

So in the same way, we call Hero’s constructor, but with Warrior’s this.
We pass Warrior’s this into Hero’ constructor

Warrior total properties = Warrior own properties + Hero properties;

We’ll add the attack() method to Warrior because its what they do. We want all instances of Warrior to be able to attack, as they should.

Linking up the Prototype

So the warrior class has properties of the Hero class. But what about the Hero’s functionalities? Let’s say the Hero’s prototype has functionality to be able to run, jump, and swim.

The warrior, being a hero, should automatically have those functionalities as well.

From javascript standpoint, when you create Warriors, it will be setup in a similar fashion like Hero. You’ll get a Warrior Prototype Object. Your Warrior’s prototype reference will point to Warrior Prototype Object. Warrior Prototype Object will add and point “constructor” back to your Warrior.

Since Hero’s prototype properties and methods are not automatically linked when you use call() to chain constructors, our Warrior will use Object.create() to link the prototypes.

Now, given Hero’s hierarchy is like so:

In order to inherit Hero prototype
1) Warrior will first disregard its own prototype object
2) Use Object.create to clone its own Hero Prototype Object.
3) re-point Warrior’s prototype to this clone.

Note:
The Object.create() method creates a new object, using an existing object to provide the newly created object’s __proto__

Object.create

w is simply a standalone object that has its __proto__ pointing to the Hero prototype object. It will be used as Warrior prototype object. But for now, let’s analyze this object:

Thus, as you can see, it does not have prototype property. It simply accesses all the functionalities of objA.


repoint Warrior’s prototype to our Hero Prototype Object clone

We simply want the type of all instances of Warrior to say Warrior {}.
It’s for clarity purposes.

We add an “attack function” to our custom Warrior Prototype Object.

We have class names’s prototype point to a literal object to denote that all
all instances of this class’s __proto__ should point to this literal object
for prototype functionalities. Since Warrior’s prototype now points to Hero Prototype object, this means all instances
of warriors have Hero Prototype Object’s prototype functionalities.

… given Hero Prototype functionality has jump, run, and swim, then our warrior will also be able to use these functionalities.

Now, all instances of Warrior can not only attack, but also jump, run, swim as well!

Double Prototype Level

Let’s create someone who has two types together.

First, we construct a Healer.

okay, so have Healer created. It derives from Hero in properties and prototype functionality.

double class power: Mage

Now let’s create a special class called Mage, where we can heal like a Healer, but also have our own Mage special ability.

Structure

You’ll see that an instance of the Mage will inherit properties and functions of its deriving object Warrior, and its deriving object Hero, and Object.

Furthermore, it will be able to use the whole hierarchy of its own prototype, which includes Warrior, Hero, and Object.


— Structure —

Mage {
name: ‘Thrall’,
level: 99,
weapon: ‘Ragnorak’,
special: ‘summons Bahamut’ }

Mage { constructor: [Function: Mage] }

Healer { constructor: [Function: Healer], heal: [Function] }

Hero { greet: [Function] }

{}

source code example

Accessing via Prototype Chain

Workout and Boxing example for JS prototype and class

Workout

First we have the Workout function class. Its declaration acts as the constructor.
We have three properties: title, datetime, and notes.

Setting the Prototype to a object literal

First, let’s define the function class Boxing. We will instantiate it, and pass it for Workout.prototype to point to.

set Workout’s prototype to a Boxing literal object

Now, the hierarchy looks like this:

All instantiation of Workout will share that literal object of type Boxing.

note:

The reason why we have a constructor property from var b is because var b (new Boxing) is the object for Workout Prototype. Thus, even though Workout is using a Boxing literal object to represent for its prototype functionality, its purpose is to be that of the Workout Prototype.

Thus, if we are to have a constructor property pointing back to Workout, any future instantiations of Workout will correctly show Workout, instead of Boxing.


output:

Workout {
price: 883,
coach: ‘Joel’,
friends: [ ‘Allen’, ‘Bundy’ ],
_display: [Function],
constructor: [Function: Workout] }
Workout {
title: ‘Monday Workouts’,
datetime: 2018-02-05T10:11:41.560Z,
notes: ’10x calisthentics’,
setNotes: [Function],
display: [Function] }

Getting property for object with prototype

Instantiate Workout and Get a property

1) Instantiate a Workout object. It basically creates an object from our definition of Workout.

2) Then let’s try using the setNotes function.

We pass in the string to newNote. In the function the ‘this’ evaluates to our Workout instantiation. We check to see if property ‘notes’ exist in Workout. It does, and we set it to our string.

We can log properties of Workout like so:


output:
boxing workout #38
2018-02-05T03:37:56.585Z
100 rounds of sparring

We then come back out to main. Since our prototype is set to Boxing object literal, let’s see what happens when we try to access property coach.

It displays the string “Joel”.

  • First, it will see if the property “coach” exists in the Workout object. It does not.
  • Because it does not, it will go to its prototype and check there.
  • The prototype object is Boxing. And Boxing does have “coach” property initiated to Joel.

Hence, “Joel” is displayed.

Keep in mind that all instantiations will share this Boxing object literal.
If we were to create another Workout object, it will display the same coach.


output:
boxinglesson1.coach: Joel
boxinglesson2.coach: Joel

Let’s evaluate the prototype to see what it looks like:


Boxing {
price: 883,
coach: ‘Joel’,
friends: [ ‘Allen’, ‘Bundy’ ],
_display: [Function] }

Let’s change the coach property to someone else:

Now, as you can see, we literally changed the prototype’s property to something “Rex”. And this gets reflected to other instantiations has their prototype property set to this object.


output:
Boxing {
price: 883,
coach: ‘Rex’,
friends: [ ‘Allen’, ‘Bundy’ ],
_display: [Function] }


boxinglesson1.coach: Rex
boxinglesson2.coach: Rex

code:

Calling prototype object’s functions

Let’s set the coach property back to Joel

Let’s look at prototype function _display

We must take heed that the this in the function belongs to the instantiated object, NOT the prototype. In our case, ‘this’ is an instantiation of Workout.

Thus, when we try to do something like this.coach, it will first check Workout object to see if it has a property called coach.

Because it does not, it will then go to the prototype and check for a coach property. In our case, it does.

Therefore, in our function, this.coach is valid (Joe) and thus, will display Joel in the function.

You will also notice we check if to see if this.display is a function. The this in question is the instantiation of Workout. Thus, we are asking Workout if it has a display function. It evaluate to true, and thus, we call Workout’s display function.

output
Boxing::_display() – display() function declared
— Workout::display(): boxing workout #38 —
@ approximately : Mon Feb 05 2018 11:43:48 GMT+0800 (CST), you will be doing:
100 rounds of sparring
Workout::display() – Your coach is: Joel
Workout::display() – Your price is: 883
————————–

Setting Properties for Objects with Prototype

When we were getting properties, JS first evaluates your instantiated object. Then if it doesn’t exist, it will go up to the prototype object. If it doesn’t exist there, then it will return undefined.

When we’re setting properties, its much more limited. Due to all instantiations share a common prototype object

we cannot set/change a prototype property through an instantiation of an object.

The only way to do is through accessing the prototype object itself like so:

Then, all instantiations of Workout will have prototype property coach “Katu”.

If you were to try to set a prototype property like this:

At first, you may think you have successfully set the prototype’s coach property.


output
—————-Boxing::_display()————–
Your cost: 883
You will be coached by: Sismundo
~~~ Boxing workout # 2 / 24
Boxing::_display() – display() function declared
— Workout::display(): boxing workout #12 —
@ approximately : Mon Feb 05 2018 11:58:22 GMT+0800 (CST), you will be doing:
Run 10 kms
Workout::display() – Your coach is: Sismundo
Workout::display() – Your price is: 883
————————–

But upon closer inspection, you’ll see that instantiations DO NOT allow you to set its prototype’s properties.

Instead, because you try to set a property that does not exist at the instantiation level, it will add the property for you. In our example, it added property coach to your Workout instantiation.

var, hoisting, and temporary deadzones (js)

ref – http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html
http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified

Hoisting is about a variable or function definition (that’s being used or initialized) being available beforehand.

For example, if we declare and initialize a variable to a string, that variable is actually available beforehand at the very top. This is because the interpreter will get all the variables, and declare them at the very top first.

global, local scope variable over-rides

Function definition declaration

Function definition declarations are hoisted.

function definition hoisting only occurs for function declarations. In other words,
when you declare the function definition, then you can simply call it.

However, when the function definition is part of a function expression, then hoisting will not work.

For example, when we have a function expression variable that takes on the function definition, we cannot hoist the function expression variable.

Function definitions as part of function expression are not hoisted

If you have a function definition, and its part of a function expression, then you CANNOT do hoisting:

Class declarations ARE NOT hoisted

class declarations are not hoisted like function declarations.

For example, if you place the following code above the Animal class declaration section, you will get a ReferenceError:

Hoisting

var is function scoped. It is available in the whole function even before being declared

Declarations are hoisted. So you can use a variable before it has been declared.
Initializations are NOT hoisted. If you are using var, ALWAYS declare your variables at the top.

We declare x globally.

There is an if block, and in it, a var is declared with the same name.
that name gets hoisted to the top of the function. The name is the same
as the global one (x), and thus over-rides it.

es5

translates to:

In es6, when we use let, it works as expected:

let will hoist the variable to the top of the BLOCK (NOT top function like var)

Referencing the variable in the block before the variable declaration results in a ReferenceError

Temporal Dead Zone

“Temporal Dead Zone” is the zone from the start of the block until the variable is declared

Can you guess what console.log(x) will print now? Well, actually, the answer is nothing — the code above will throw a ReferenceError due to the TDZ semantics. That is because let/const declarations do hoist, but they throw errors when accessed before being initialized (instead of returning undefined as var would).

let and const declarations define variables that are scoped to the running execution context’s LexicalEnvironment.

In other words, the variables are created when their containing Lexical Environment is instantiated. This means whenever control flow enters a new scope (e.g. module, function or block scope), all the let/const bindings belonging to the given scope are instantiated before any code inside of the given scope is executed — in other words,

let/const declarations DO HOIST

…but may not be accessed in any way until the variable’s LexicalBinding is evaluated.

This is the Temporary Dead Zone

A given let/const-declared binding can’t be accessed in any way (read/write) until control flow has evaluated the declaration statement — that does not refer to the hoisting, but rather to where the declaration actually is in the code.

And the last part:

If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.

This simply means that:

Is equivalent to:

Trying to access x in any way before control flow evaluates the initializer (or the “implicit” = undefined initializer) will result in a ReferenceError, while accessing it after the control flow has evaluated the declaration will work fine. i.e reading the x variable after the let x declaration in both samples above would return undefined.

Does the code execute without errors? What is the value of x after the code executes?

First off, remember that a let/const variable only counts as initialized after its initializer has been fully evaluated — that is, after the assignment’s right-hand side expression has been evaluated and its resulting value has been assigned to the declared variable.

In this case, the right-hand side expression tries to read the x variable, but x’s initializer has not been fully evaluated yet.

Thus, trying to read x at 2) results in a TDZ, and thus will throw a ReferenceError.

— in fact we are evaluating it at that point — so x still counts as uninitialized at that point and thus trying to read it throws a TDZ ReferenceError.

Other Examples

In the first line, the f() call makes control flow jump to and execute the f function, which in turn tries to read the b constant which, at this point in the runtime, is still uninitialized (in TDZ) and thus throws a ReferenceError. As you can see, TDZ semantics apply when trying to access variables from parent scopes as well.

Here, we have parameters a and b defined in the IIFE. Parameters are evaluated from left to right. At the left, we have a = 1.
Then the next parameter b takes on a, which at that time, evaluates to 1, thus b = 1.

The a, b are parameters. They are bound to the IIFE. thus, parameter b’s scope is in the IIFE. b gets hoisted. When a tries to assign b, it will throw a ReferenceError. Because b does not have a value yet.

more examples…

First we implement Numbers class with a simple constructor where we initialize

references, values in Javascript

There are no pointers in Javascript

In JavaScript, a variable may store two types of data:

  • primitive
  • reference

JavaScript provides six primitive types as undefined, null, boolean, number, string, and symbol.
Reference are Objects and Arrays.

When you assign a variable a value, the JavaScript engine must determine whether the value is a primitive or a reference value.

If the variable stores a primitive value, when you manipulate its value, you are working on the actual value stored in the variable. In other words, the variable that stores a primitive value is accessed by value.

Unlike the primitive value, when you manipulate an object, you are working on the reference to that object, rather than the actual object. In short, a variable that stores an object is accessed by reference.

Assign by primitive values

Another explanation

Assign by Reference

When you assign a reference value from one variable a to another variable b, the value stored in variable a is the address an actual object in the heap. That value is also copied into the location of the new variable b.

The address of the actual object stored in the heap is now stored in both variables a and b. As the result, both variables are pointing to the same object.

Thus, if you were to modify by accessing the properties of the object, it will change the object in the heap because you are essentially “dereferencing” it.

If your reference gets assigned to new value, it now points to a whole different object in the heap.

Create new Reference

When a variable is assigned to a new Compound Value (Object, Array), that variable points away and onto the new Compound Value.

Passed by Value

In JavaScript, all function arguments are always passed by value. It means that JavaScript copies values of the primitive variables that you pass to a function into local variables. Any changes that you make to the local variables inside the function does not affect the arguments that you passed in. In other words, the changes to the arguments are not reflected outside the function.

http://www.javascripttutorial.net/javascript-pass-by-value/

Compound values are Pass by value of the reference (function parameter passing)

When compound values (objects/arrays) are passed to functions, it passes the value of the reference. Simplest way is to just think of it as the parameter pointing to the compound object’s. Due to the parameter having the value of the reference of the compound value, if we access the property and change it, we are literally dereferencing the compound value, and changing it. Thus, the compound value will change.

If the parameter is assigned to something else, we are literally pointing it away to something. It will have the value of another reference.

Change original value in compound variable passed into a function

Compound variables are passed into a function via value of the reference. Hence, the only way it to literally wipe out its original values, then push new ones.

Reference a Compound Value

slice() creates your own array.
For primitives, it copies the values and each array has its own values.

But because we are dealing with objects, the array’s element will simply point the the object.

How to store a scalar primitive value through assign-by-reference?

Storing a scalar primitive through assign-by-reference is very simple. Just wrap a compound value outside of it and that’s it.
In our case, we put a primitive value inside of an object. Passed that object into a function, and change that value.

Why use Virtual (C++)

ref – https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c?rq=1

Simple Over-riding

Without “virtual” you get “early binding”. Which implementation of the method is used gets
decided at compile time based on the type of the pointer that you call through.

OUTPUT:

Constructing Shape
Constructing Circle

Constructing Shape

SHAPE: Draw function
SHAPE: Draw function

Using Virtual

OUTPUT:

Constructing Shape
Constructing Circle

Constructing Shape

SHAPE: Draw function
Circle: draw function

Arrays (js)

https://stackoverflow.com/questions/931872/what-s-the-difference-between-array-and-while-declaring-a-javascript-ar
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://medium.com/@gamshan001/javascript-deep-copy-for-array-and-object-97e3d4bc401a

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array’s length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array’s length property minus 1. Using an invalid index number returns undefined.

functions are all in Array.prototype

In your browser’s console, type Array.prototype and press Enter. You’ll be able to see all the functionalities used.

Create an Array

Access (index into) an Array item

Loop over an Array

Add to the end of an Array

Remove from the end of an Array

Remove from the front of an Array

Add to the front of an Array

Find the index of an item in the Array

Remove an item by index position

Remove items from an index position

Copy an Array

How to copy array

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

The code above creates clone of the original array; keep in mind that if objects exist in your array, the references are kept; i.e. the code above does not do a “deep” clone of the array contents.

…various ways

ref – https://www.briangonzalez.org/post/copying-array-javascript

There are many ways to copy an array in JavaScript, and with ES6, that list has grown even longer.

Here are some options I came up with (with the help of Twitter). They are shown in order of performance.

It is helpful to clearly distinguish an array index from an object property name.

All indexes are property names

but only property names that are integers between 0 and 2^32–1 are indexes

All arrays are objects, and you can create properties of any name on them.
If you use properties that are array indexes, however, arrays have the special
behavior of updating their length property as needed.

Note that you can index an array using numbers that are negative or that are not integers.
When you do this, the number is converted to a string, and that string is used as
the property name.

Since the name is not a non-negative integer, it is treated as a regular
object property, not an array index. Also, if you index an array with a string that happens
to be a non-negative integer, it behaves as an array index, not an object property.
The same is true if you use a floating-point number that is the same as an integer:

Another example:

output:

[ ‘ricky’,
‘bob’,
‘grandma’,
‘grandpa’,
‘shark’,
hobbies: ‘badminton, hill climbing, etc’,
lastName: ‘Tsao’,
‘-1.23’: ‘decimal’,
true: ‘DESTROY’,
false: ‘CREATE’ ]

5

The fact that array indexes are simply a special type of object property name means
that JavaScript arrays have no notion of an “out of bounds” error. When you try to
query a nonexistent property of any object, you don’t get an error, you simply get
undefined. This is just as true for arrays as it is for objects:

a = [true, false]; // This array has elements at indexes 0 and 1
a[2] // => undefined. No element at this index.
a[-1] // => undefined. No property with this name.

Array Literal


output:

BMW
undefined
[ ‘Saab’, ‘Volvo’, ‘BMW’, dealership: ‘longo, CA’ ]

What’s the real difference between declaring an array like this

var myArray = new Array();
vs
var myArray = [];

The difference between creating an array with the implicit array and the array constructor is subtle but important.

When you create an array using

You’re telling the interpreter to create a new runtime array (Array specs created at runtime). No extra processing necessary at all. Done.

If you use:

You’re telling the interpreter, I want to call the constructor “Array” and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.

If you do not redefine Array, then its not a problem. However, if someone decides to redefine it and implement the constructor, then everything goes haywire:

In other words, the difference is that using the new operator causes the interpreter to take all sorts of extra steps to go to the global scope, look for the constructor, call the constructor and assign the result… which in the majority case is going to be a a runtime array. You can avoid the overhead of looking for the global constructor by just using []. It may seem small, but when you’re shooting for near real-time performance in your app, it can make a difference.

other examples:

Performance Hit

https://jsperf.com/create-an-array-of-initial-size/2

Looks like creating literal array, using a while loop to initialize it, is the fastest among browsers.

For loop with push, is another good alternative

Deep Cloning

sort

if comparison is + (say, 100 – 40) do sort (if comparing 100, 40, it will sort to 40, 100)
if comparison is – (say, 40 – 100) DO NOT sort. leave as is.

So if we we get [100, 40]. 100 – 40 = 60. truthy, sort it. [40,100]
if we get [4, 20]. 4 – 20 = -16. falsey. don’t sort it. [4,20]

In the end, we get smallest to largest.

What if we want to sort largest to smallest?

so in comes [100(a),40(b)], we don’t want to sort in this situation and hope for a false.
So we say b-a. 40 – 100 = -60 don’t sort
in comes [40(a), 100(b)], we want to sort this, and try to give it a truthy. b-a, 100 – 40 = 60.

Now, we get largest to smallest.

getter setter (JS)

ref – https://javascriptplayground.com/es5-getters-setters/

this is ugly:

But this is ugly, and requires the users of your object to care that the properties are related; in a more complex example, that might not be as obvious as with names. Luckily, there’s a better way, added in ECMAScript 5.

we see that we have a get/set for property fullName.

Following them is the property they relate to (fullName) and a function body that defines the behavior when the property is accessed (name = person.fullName) or modified (person.fullName = ‘Some Name’).

In other words, get simply means to access the data, so we naturally return the property data. set means to set some properties in the object through one parameter. We can only provide one parameter because in an assignment, there’s only one parameter on the right side.

These two keywords define accessor functions: a getter and a setter for the fullName property.

When the property is accessed, the return value from the getter is used.

When a value is set, the setter is called and passed the value that was set. It’s up to you what you do with that value, but what is returned from the setter is the value that was passed in – so you don’t need to return anything.

The official way: Object.defineProperty

This method takes three arguments.

1) The first is the object to add the property to

2) the second is the name of the property

3) and the third is an object that describes the property (known as the property’s descriptor).

But why do it this way?

The advantage here isn’t immediately apparent. Other than being able to add properties after creating the initial object, is there a real benefit?

When you define a property this way, you can do much more than just define a setter or getter. You may also pass following keys:

configurable (false by default): if this is true, the property’s configuration will be modifiable in future.
enumerable (false by default): if true, the property will appear when looping over the object (for (var key in obj)).

We can also define properties that don’t have explicit getters or setters:

This will create person.age, and set it to the value 42. It’s important to note that this property isn’t writable. Calling person.age = 99 will have no effect. In this way you can create read-only properties. If a property has a value key set, it cannot have a getter or setter. Properties can have values or accessors, not both.

Not only that, but because the enumerable property defaults to false, this property will not appear when we loop over the object’s keys.

If we wanted to make a property writable, we would need to set the writable property:

Example 1


output:

10
7.071067811865475
7.071067811865475

Example 2

Example 3

Chaining Prototype

https://hackernoon.com/inheritance-in-javascript-21d2b82ffa6f

Example of chained prototype.

Hierarchy basics – Object

Firstly, all functions derive from “Object”, where “Object” is the default base of all javascript objects. The idea behind how hierarchy is laid out in JS is that the Object definition references an empty object called Object Prototype via a reference called “prototype”.

This Object Prototype object has a constructor reference pointing back to Object. Now all prototype objects of any function definitions you declare is an object literal. Since its an object literal, it will have a __proto__ reference, and this reference will be pointing to Object Prototype.

Example of custom Identification function

So let’s see how this works. Let’s declare a function definition called Identification. It automatically sets you up with a Identification object definition, and any related properties. In our case, we have a property called ‘name’, initialized to Ricky.

Furthermore, it will have a prototype reference to an empty literal object called “Identification Prototype”. This empty Identification Prototype will then have a constructor pointing back to our Identification object. More importantly, since this prototype object is a literal object, it will have a __proto__ reference pointing to Object Prototype.

If you were to simply create this code, and then evaluate the prototypes, constructors, and __proto__ references, you’ll see the output like so:

Identification.prototype references its own Identification Prototype object.
Identification.prototype –> Identification {}

The prototype object’s constructor references back to the Identification definition.
Identification.prototype.constructor –> [Function: Identification]

Since Identification.prototype is an object literal, it has a __proto__ and is pointing to Object Prototype.
Identification.prototype.__proto__ –> {}

Naturally, the constructor of the Object Prototype is a function of Object
Identification.prototype.__proto__.constructor –> [Function: Object]

Adding a function to Identification’s prototype

Appending any kind of functions to Identification prototype is straightforward. We are appending to the empty Identification Prototype object.

When we analyze Identification Prototype, we’ll see that the function has been added to it. As expected the constructor is still on Identification.

Identification.prototype –> Identification { getName: [Function] }
Identification.prototype.constructor –> [Function: Identification]

Person basics

In the same way Identification was created, let’s create a Person object.
When the Person function definition is created, it will automatically have a prototype reference to an empty object literal called “Person Prototype”. Person Prototype will have a constructor reference back to Person. Naturally, Person Prototype will have __proto__ pointing to Object Prototype.

As expected we have:

Person.prototype.constructor –> [Function: Person]
Person.prototype –> Person {}

With Identification and Person definitions, we now have a hierarchy like this:

Now, I want Person to prototype information from Identification because naturally, each person have some sort of identificaion. Prototypes can only reference objects, thus, let’s create an instantiation of Identification. We’ll have first and last name to “ricky Tee”.

Remember, any kind of object literal (or instantiation) will have their __proto__ pointing to their own Prototype.

So in our case, since we made an instantiation of Identification, our instantiation’s __proto__ will reference Identification Prototype (along with any appended properties and functions)
identificationInstance.__proto__ –> Identification { getName: [Function] }

We then check what constructor our __proto__ is pointing to. Naturally, it is Identification.

identificationInstance.__proto__.constructor –> [Function: Identification]

Accessing the reference constructor gives the same result. The reason why is because when we try to access “constructor” on the instantiation object, it does not find it. So it goes up the hierarchy to its __proto__ and tries to find it there. __proto__ is Identification Prototype, and here we find constructor pointing to Identification.
identificationInstance.constructor –> [Function: Identification]

Chaining Person to Identification

Finally, we are set to chain one prototype to the next.

Specifically, since we have an Identification object to chain to, we assign Person’s prototype reference to it.

As you can see from the picture, Person’ prototype points AWAY from Person Prototype and onto the Identification instance.

Let’s check out Person’s prototype and constructor references now:

Person.prototype –> Identification { firstName: ‘ricky’, lastName: ‘Tee’, friends: [] }
Person.constructor –> [Function: Identification]

As you can see, prototype references Identification. The reason why is because Person.prototype points to the instantiation of Identification. It has its standard Identification properties as you can see from the output.

Next, we try to access constructor in Person. There is no constructor property in Person, so it goes to prototype in order to find constructor. Its prototype is the instantiation of Identification and does NOT have constructor either. It then goes up the hierarchy 1 more level at __proto__, which points to Identification Prototype. At this point, it sees that the constructor references Identification. Thus, that is why Person.constructor is Identification.

Solution

After understanding the basics above, its obvious that all instantiations of Person will share the same Identification prototype. That’s not good. In order to have each Person instantiation have their own Identification, the solution is to Inherit properties. We do this by having Person’s constructor call on Identification’s constructor using ‘this’. That way, Identification can start appending properties to Person’s ‘this’. In other words, we let Identification get Person’s this, then add properties to it.