Category Archives: javascript

The Execution Context – Creation and Hoisting

output:


Called b!
Hello World!

Now lets hoist our execution to the top.

output


Called b!
undefined

Now try removing the a

Now, you’ll get an error saying ‘a’ is not defined.

Reason – 5:00

Execution Context:

(1st) Creation Phase (global obj, this) – it sets up memory space for created variables and functions. This step is called Hoisting.

It’s not moving code on top of page. All it means is that before your code is being executed, the compiler has parsed your code, and those variables and functions already exist in memory. During execution, they exist and we can access them.

The function in its entirety (including its name) is placed into memory space.

(2nd) Execution Phase – However, in the next phase of executing your code, when it comes to variables, because it does not know ultimately what the values will be until it starts executing your code, will instead put a placeholder called undefined. It just means we don’t know what the value will be.

Hence, all javascript variables initially are set to undefined

The Global Environment and the Global Object

Whenever code is run, it is run inside an execution context.

Execution context being first created, then run.

For example, the global execution context creates 2 things for you:

– a global object
– this variable

Then when you run it, the ‘this’ will point to the global object for you to reference. Anything you implement will also be attached to this global object.

Let’s see how it works:

1) create an empty html page
2) create an empty JS file
3) include this empty JS file in the html page

Now run the html page. Look in Inspect, and under Console tab, type this

You’ll see the Window object.

The execution context was created by the JS engine. And it decides the value of what ‘this’ be. In the currently situation, this is pointing to the window object.

If you’re running JS in Node, you’ll get a different object and ‘this’ will be pointing to that instead.

An execution context was created at the global level as a global object. ‘this’ refers to the window object.

Global simply means ‘not instead a Function’

Your definitions being attached to the global object

The execution context is created

the ‘this’ reference and ‘window’ object are available.

Anything you create globally (the variable ‘a’ and function ‘b’) will be attached to the global object:

console.log(window.a); // Hello World
window.b() // test

When code is executed, an execution context is created.

At the base level, you have a Global Object.
If you are in the browser, that global object is ‘window’ object.

You get a special variable called ‘this’, which references the global object.

Dependency Injection (js)

ref – https://stackoverflow.com/questions/20058391/javascript-dependency-injection

Problem

So we have a Printer class with a prototype function ‘print’. It prints something to console depending on a public property in the constructor.

It’s not flexible because it ONLY has this feature of printing. The functionality can’t be switched out.

In order to make it more flexible:

1) we use a driver property to take on new classes with different printing functionalities.
2) Then in our print function, we simply call the functionalities.

In this example, we can just add/remove functionalities in Driver. As long as the name driverPrint is being executed in Printer, then we’re good.

So our Printer class is now more modular, clean and easy to understand but there’s still some inflexibility yet again.

Any time you use new keyword you are actually hard-coding something

In this case you are constructing a driver inside your Printer which in real world is an example of a printer that comes with a built-in driver that can never change!

A better version is to inject a driver at the time we construct a printer meaning you can make any type of printer, color or black&white, because this time the driver is being made in isolation and outside the Printer class and then given (INJECTED!) into the Printer…

The problem presented here is that we are creating a new printer each time we need our printer to print with a different driver! That is because we are passing our driver of choice to the Printer class at the construction time.

or example if now I want to do a color print I need to do:

Provide Setter

Providing a setter function can dynamically let you switch out different Drivers, thus switching up on your functionalities.

Dependency Injection using Duck Typing

ref – https://stackoverflow.com/questions/12762550/example-of-javascript-duck-typing

Functions in JavaScript are versatile. They can be used as subroutines, methods, constructors, namespaces, modules, and much more.

The reason people advise against using prototype chain inheritance (by using instanceof) in JavaScript is because it hides the true power of JavaScript. Functions are just as expressive if not more expressive than objects. This has been proven by Alonzo Church who’s work, Lambda Calculus, is Turing Complete.

To answer your question directly I’ll use functions to create a Turtle, a Lion and a Dolphin. Then I’ll demonstrate how a turtle is an OceanAnimal and a LandAnimal, how a lion is only a LandAnimal, and how a dolphin is only an OceanAnimal. I’ll conclude by explaining what is duck typing.

First let’s create the constructor for an OceanAnimal:

Next we’ll create the constructor for a LandAnimal:

Next we’ll create the constructor for a LandAnimal:

What’s happening here?

Okay, we want Turtle to inherit from both OceanAnimal and LandAnimal. So we’re calling LandAnimal.call(this) and OceanAnimal.call(this).
In this way we’re using the OceanAnimal and LandAnimal constructors as mixins. Thus Turtle inherits from both OceanAnimal and LandAnimal without actually becoming of type OceanAnimal or LandAnimal.

Connecting through prototype chain can work but it will take more work via connecting their prototypes

Another thing to notice is that we’re setting the type property on the prototype of Turtle instead of inside it. This is because type is the same for all turtles. Thus it’s shared. The name of each turtle on the other hand may vary and hence it’s set inside the constructor.

Since Lion is a LandAnimal we only mix in the LandAnimal constructor.

Similarly for a Dolphin:

Now that we have created all the constructors let’s create a turtle, a lion and a dolphin:

Awww, now let’s set them free:

Okay, so what’s duck typing? We know that yoyo is an OceanAnimal and a LandAnimal. However if we do yoyo instanceof OceanAnimal or yoyo instanceof LandAnimal then it returns false. What?

You: Stupid JavaScript. A Turtle is an OceanAnimal and a LandAnimal!
JavaScript: Not from where I’m standing. All I know is that it’s a Turtle.
You: But if it swims then it’s an OceanAnimal, and if it walks then it’s a LandAnimal.
So since JavaScript is such a party pooper we’ll have to create our own test to check if an object is an OceanAnimal and if it’s a LandAnimal.

Let’s start with an OceanAnimal:

Similarly, for a LandAnimal:

So now we can use isOceanAnimal(yoyo) instead of yoyo instanceof OceanAnimal, and isLandAnimal(yoyo) instead of yoyo instanceof LandAnimal; and both these functions will return true for our beloved yoyo. Yay!

Decorator Pattern (js)

Standard Example

test

Decorator example 1 – Dressing up a Hero

ref – https://kickoff.tech/2019/07/26/mau-thiet-ke-huong-doi-tuong-decorator-pattern/

First, we define the hero. We give it two properties:

– strength: a characteristic of this hero.
– decorators: an array of references that point to things that we want to “decorate” the hero with.

Each decorator item that the Hero wears will give him extra strength. Thus, we basically add up how much strength he has by how each item bestow their strengths.

In order to see what our Hero is wearing, we’ll implement a render function that basically iterates through the list of decorators and returns the string names.

Finally, we have decorate list. It’s like an inventory list. It keeps track of the items the hero wears.

Now, we implement Hero Decorator. It is a class that does an action to put and use the items onto the Hero.

We first keep a hold on the name and strength attribute of the item we’re adding. For example, “gloves”, which gives us strength percent of say 10.

Then we just have the get functions that return those data.

Let us create an item Hat. Now, we use Item to call and use its property initialization with our Hat object.
Thus, we get property name, percentStrengthen for our Hat object. We also inject our values name, 10 to initialize those properties.

In order to have our Hat be able to use Item functions getName and getPercentStrengthen, we must create an object with its __proto__ pointing to Item.prototype. This object will act has Hat’s prototype object.

Then we point Hat.prototype to this Hat prototype object. At this point, we have successfully connected the chain.
Then for verification and correctness, we must point Hat’s prototype object’s constructor reference back to our Hat.
That way, when we use typeof for our object, it will say ‘Hat’, instead of ‘function’.

Now let’s create Ring. We need to have basic properties created using Item because we are trying to be a child object. We initialize those properties with our name, and 20 strength. Then we connect our Ring to the prototype chain of our Item.

1) Now we create a hero with 5 strength. We automatically have an empty decorator property list ready to hold items that we pick up along the way.

2) We put a Mage Hat into the decorator list.

3) We put a Ring into the decorator list.

4) We then execute Hero’s render function, which goes through each item in decorator list and logs.
Then we calculate total strengths. Similarly, we iterate through the decorator list and append each value to our total strengths.

So as you can see the concept here is that:

1) We use parent class Item to tell us what properties we want to use. Then, other detailed items such as gloves or rings, are created from this Item parent class.

2) On the Hero himself, we use a list to keep track of all the items.

3) Now, when we want to render the Hero’s status, or look at its strength gauge, we iterate through this list to get the info we need.

Decorator example 2 – Validate a Form

ref – https://robdodson.me/javascript-design-patterns-decorator/

Here we want to validate a form by using a list of properties.

We do this by using JS’s associative array (dictionary) properties characteristics.

What I mean by that is there are two ways to access an element:

They both do the same thing, and will give you the same value.
Thus, we can use this technique to use String to pick what properties we want to access.

The other important thing is that after accessing said property, we simply call ‘validate’.
If each of these properties implement a validate function, we can simply loop through all those properties and call validate.

For example, let’s create a Validator constructor function that has an errors property list to hold errors.
We also have a decorator list to keep track of what we want to validate.

Then we create a ValidatorDecorator constructor function. It will be used for our Validator object to call so that it can use ValidatorDecorator’s functionality, but using its own Validator ‘this’ object. The ‘validate’ functionality that ValidatorDecorator can be applied to our Validator instance. Whatever error, messages, and logic gets calculated, we store in our Validator instance’s error list.

So the way how its done is like this:

let tmp = new ValidatorDecorator();

tmp[‘hasName’].validate will then get you the validate function of property hasName
tmp[‘hasAge’].validate will then get you the validate function of property hasAge
tmp[‘hasZipCode’].validate will then get you the validate function of property hasZipCode

When we execute validate, we use call to use the current ‘this’ Validator object.
In our Validator’s validate function, we pass in the form.

Then, depending on how we decorated our checks, we would run our form through those checks. For example, say I want to check for name, age, and zip code.

So initially I would add those to my decorate list like so:

Now I am ensured that whatever form comes through, I will check for if:

– the name is ricky
– the age is 39
– the zip code is 218000

Now, let’s implement the validate function.
For our ‘form’ parameter, we loop through all of the validators to check for name, age, and zipcode.
We access each check’s property by using the string ‘name’, where ‘name’ is hasName, hasZipCode..etc.

Since each of these properties have a function called validate, we simply execute it with our ‘this’ object.

note: Validator’s property decorators in the picture refers to decoratorList in our sample code.

Supplement

you can also use a static property like so

Decorator example 3 – Create a lunch bowl

Here, we use call again to use inheritance to create and initialize properties.
First, we create a Bowl, with parameters for customer name, bowl name, and price of the bowl.

Then we have an items list to hold what we want applied to the bowl.

we also have a print function that simply logs the attributes of this bowl.

Now, we create a parent class called SideDish. It has the properties price and name.

Now, in our Hero examples, we have a Hero that uses a list called decorators. Then it has Items | Hat as parent/child object. We add the children objects into Hero’s decorators and then the Hero would iterate through that decorator to update its data. Hence, the Hero object references the Items. It’s one way from Hero to Items.

Then in our Validator example, we have Validator, that also uses a list called decorators. It uses a ValidatorDecorator function along with Object.call. The Validator object iterate through the list of decorators, executes validate functions in ValidatorDecorator via associative property strings. Those validate functions uses the Validator object to access its errors list to update its data. Hence Validator object and ValidatorDecorator object reference each other.

Now, in our Bowl example, we have a BowlDecorator that acts as child of SideDish. It holds a reference to the Bowl. Then it uses Object.call to initialize data about the side dish. Once that’s done, it calls updateBowl to update the bowl’s data. It acts as a middle man where its parent class is the side dish, and it literally puts the parent class data into a bowl.

Let’s look at an example. Say we have Oxtail. We make it a child of BowlDecorator and use Object.call with a bowl.
What this means is that Oxtail have properties:

– cost
– name
– bowl

Then we include Oxtail in BowlDecorator’s prototype chain. This allows us to call BowlDecorator’s prototype functions i.e updateBowl.

We do the same for JasmineRice and Carrots

Now, let’s see how it will be used. We allocate a Bowl.

Once that bowl has been created, we can simply create new Side Dishes and pass in the bowl.
The bowl will be updated by the Side Dish’s call to BowlDecorator.call(…)

BowlDecorator will then do its job of decorating the bowl with the Side Dish information via its prototype updateBowl function.

output

ted have ordered Hearty Oxtail
Total cost of bowl is 86
-- items in this bowl --
[ 'Stewed Grassfed Oxtail',
'Jasmine Rice',
'Buttered Idaho Potatos',
'Oregeno Sauteed Carrots' ]

export/import and singleton patterns (js)

ref – https://blog.bitsrc.io/understanding-design-patterns-in-javascript-13345223f2dd

export import

First let’s take a look how we export our implementations.

When you put keyword export in front, it means we’re exposing it for others to use.
Any other objects that do not have this keyword will not be exposed. Thus giving it privacy.

utils.js

Another to simply export all of them together.

utils.js

In order to use them, we use import in two ways:

one at a time

or just import the whole module.

renaming an import export

renaming an export

renaming an import

Singleton Pattern

A Singleton is an object which can only be instantiated only once. A singleton pattern creates a new instance of a class if one doesn’t exist. If an instance exists, it simply returns a reference to that object. Any repeated calls to the constructor would always fetch the same object.
JavaScript has always had singletons built-in to the language. We just don’t call them singletons, we call them object literal. For example:

Because each object in JavaScript occupies a unique memory location and when we call the user object, we are essentially returning reference to this object.
If we try to copy the user variable into another variable and modify that variable. For example:

We would see both of objects are modified because objects in JavaScript are passed by reference not by value. So there is only a single object in the memory. For example:

Singleton pattern can be implemented using the constructor function

So originally, in js, we declare a function like so:

This function is an object. It has a this that points to the global environment (es5), or null (es6).
Hence if you were to call it like so:

it would simply execute the function implementation and log the statements. As for this, in es6, it would be null and if you try to access property name on null, it will crash.

Or if you’re in es5, it’ll get the Window object and attach the property name on there.
You are working on the Window object, and not an object of your own.

Therefore, you have two choices. You’re either running the function as a group of executions, or you’re manipulating the global window object (es5), or simply running into access errors because ‘this’ is null in es6.

In order to instantiate your own object, you need to use new. When you’re using ‘new’, it will create an instance of an object for you. Then point the this of the function onto the object literal. Then, your joy variable reference will be pointing to that object instance.

In your function implementation, your ‘this.name’ will have that object instance add a property name. Then initialize it to the newName parameter, and so forth.

Now, in our case, we want a singleton. So under this environment, the key idea is that we let its normal workings of ‘this’ point to an object instance do its thing. The only difference is, we need to use a global variable to keep count and maintain the singleness of this singleton.

We do so by using this logic:

Basically we declare a variable reference.

If it’s null, we point it to the function object.
If the instantiation of the function object is used again, we check for the instance.
If that instance is already pointing to a function object, we return the same instance.

Thus, this ensures singleness.

Singleton using Module Pattern

Can also use module pattern to implement the singleton. But we must conform to the rules of the module pattern.
The rules is that it returns an object that exposes properties for others to use.
Thus, everyone else will be call for an exposed property (getInstance) that will only give them that same single literal object.

In order to do this, we use the same concept of an instance to checker whether it’s already pointing to an object.

1) We declare the instance variable.

2) When others call that exposed property, we which checks to see if it’s already pointing to an object.

3) If it is, simply return our instance. If it’s not, we return an object literal.

This way, we ensure singleness.

why we need to bind functions in ReactJS components

ref – https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/

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.

Hence, if we do not bind a function in a ReactJS project, the ‘this’ object is undefined.

Thus, that is why you need to bind it in the constructor:

Creating reference function and binding it in onChange handler

Say we create a handler for onChange. But we want to give it more parameters. How do we do it?

First, understand Apply

First, we create a function where its ‘this’ executes a callMe function.

callMe was not defined, so we use ‘apply’ to have the ‘this’ reference our own custom object.

We put in object with a callMe function like so:

When you use apply, you execute myChangeHandler right away and that is why you’ll get the log right away. In myChangeHandler, this.callMe executes right away.

Now, when using bind it DOES NOT EXECUTE RIGHT AWAY. It will return a function reference. You must exeucte it in the future in order to use it.

That is why when you’re in the html code, and you need to implement an onChange handler, you need to do this:

First, when you use bind, it returns a function reference which is what you need. You do not want to execute a function right away. You need to give a reference to a function for future executions. That is why bind works, and call/apply does not work here.

Second, naturally, any values you give, will be designated as the parameter to the handler function

Hence, the parameter type will have the value SEARCH_STARTS_WITH.

Finally, notice we also have an event object parameter at the very end. The reason why is because when you click in the future, the searchWithHandleChange will be called in the future. The system will dynamically give you an event object along with the click. It will be appended as the last parameter in your param list.

dynamic data in the DOM with css and js effects

ref – https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript

index.html

1) we write an HTML page with a ul list that has three items.
2) apply some js effects to our li elements
3) create a button that would dynamically add a li item

script.jsjs

We have a simple script that attaches inline css and js effects to all the li elements.

Now, when you run the page, you’ll see the list with its effects. Specifically, some js added inline CSS effects and a click handler that displays the text of the li element.

This is because when the page has finished putting its DOM together, it runs the script.js file, and it also declares the addItem function.

The execution of script.js file makes it so that it applies the inline CSS and click handler to the existing li elements in the DOM.

The declaration of the addItem function exists to that later when the user clicks on the add button, we have a function that can run.

Thus, all js code executed so far comes after the readiness of the DOM.

Now, when you click on the li element, it would respond to the click event like so:

However, there is a problem. When you click on the ‘add’ button to dynamically add an item, you don’t see the inline css effects anymore. If you try clicking on the li elements, nothing happens:

CSS

Inline CSS is when we attach the CSS to the element itself.
Internal CSS is when we declare CSS on top of the html page.
External CSS is when we attach the CSS code in a separate file.

Thus, when we use inline CSS, it only applies to the loaded DOM. Any dynamic new data that comes in after won’t get the CSS effects.

In order to have CSS effects on all elements, including later added dynamic elements, simply use internal or external CSS.

In your script.js remove the css:

Then in the head tag of the html page, add some internal CSS:

Now, when you add dynamic li elements, you’ll see tht the CSS is applied immediately:

Note that you can also apply some inline CSS when the items were created and added to the DOM. That will work too, but it’s cumbersome, and we miss out on the benefits that CSS brings us:

Events were not applied

If you were to click on the li items, you’ll notice that even though internal/external CSS will aways apply to past, current, and future DOM changes, JS events won’t be applied to future DOM additions.

In order to apply it, we’ll implement an add event listener. It simply listens for a certain event, and when that event happens, it executes code.

script.js

Now when you refresh the page, every newly added li elements will the click event.

In jQuery, you’d use the .on function

In this way, all dynamically added elements will have your chosen events bound.

In certain situations when you are working with templates, a lot of effects are applied by JS on data elements. When these data elements are added dynamically, you won’t see your effects for these newly added elements. What you have to do is:

1) Make sure effects on data that are added/removed are CSS based.
2) Using addEventListener or .on, you’ll have to apply these effects on the fly.