Prototype in Javascript

What is prototype in JavaScript?

An encapsulation of properties that an object links to. Simply put it allows you to share functions or properties with every single object of some specific type. Now every JavaScript object has a prototype. The prototype is also an object. All JavaScript objects inherit their properties and methods from their prototype.

There are two types of prototypes:

1. A function prototype is the object instance that will become the prototype for all objects created using this function as a constructor.
2. Where as an object prototype is the object instance from which the object is inherited.

Let us take an example:

function Employee(name)
{ 
  this.name = name;
}

Now the Employee.prototype is the function prototype. If I create an object of type Employee, then it has an object prototype, which is accessible as

employee.__proto__

Please note that the Employee.prototype is pointing to the same object as employee.__proto__.

var employee = new Employee(name);
Employee.prototype ===  employee.__proto__

Similarly, if I create an another employee object then also a new object is  pointing to the Employee.prototype object.

var employee1 = new Employee(name);
employee1.__proto__ === employee.__proto__  === Employee.prototype

It means that the prototype object is shared between objects of type Employee.

How the property is read by the javascript engine?

If I type employee.salary(), it will return an error that salary method does not exist. However, if I can modify the prototype object, so that the salary() function is attached with the Employee prototype then the function salary() will be available for every single object of type Employee.

Employee.prototype.salary = function () {return 0; };

Now employee.salary() will return 0. Which means that if the object does not have a property then javascript engine will check with __proto__ object.

You can check who owns the salary object with this line of code:

employee.__proto__.hasOwnProperty('salary')

It will return true because salary is assigned to Employee prototype.

How can I change prototype object?

If you assign something to the prototype variable, a new prototype object is created. However, any existing objects are still pointing to the old prototype. so far I have two variables, employee and employee1. Both of these variables are pointing to the same prototype. Which means that the employee.age and employee1.age will return the same type i.e. undefined. However, if I change the value of a prototype age of an Employee like this:

Employee.prototype = {age: 10}

Then employee.age == employee1.age are still same, pointing to the type undefined but employee.age != Employee.prototype.

When I create a new object of an Employee like this:

var employee2 = new Employee();

The employee2 is pointing to a new prototype and employee2.age will return 10.

How inheritance works?

  • Make a call to parent function by using <base function>.call(this, <parameters>).
  • Set prototype for derived class.
  • Set prototype.constructor for derived class.
'use strict'
 
 function Employee(name){
 this.name = name
 }
 
Employee.prototype.age = 5; 
Employee.prototype.calculateSalary = function() { return 1000 };

function Manager(name) {
 // if you are not going to call the base constructor then
 // you are not going to have a name.
 Employee.call(this, name) // 1 
 this.hasCar = false;
}
 
Manager.prototype = Object.create(Employee.prototype); // 2.
Manager.prototype.constructor = Manager; //3.
 
var manager = new Manager('test');

console.log(manager.calculateSalary());

 How Prototyping is done with Classes?

'use strict'
 
 class Employee {
 constructor(name) {
 this.name = name;
 } 
 
 calculateSalary() {
 return 1000;
 }
 }
 
 class Manager extends Employee { 
 
 constructor(name, hasCar) {
 super(name);
 this.hasCar = hasCar;
 } 
 }

var manager = new Manager('test', true);
 console.log(manager.calculateSalary());

 

 

 

Playground – Javascript Object Properties.

How to define properties?

There are many ways to do this:

1. Assign a Json object aka bracket notations.

var employee = {
 name : {first: 'Vinod', last: 'Kumar'},
 gender: 'M'
};

2. Use . operator

var employee.fullName = "Amit Malhtora";

3. Use [] operator

var employee["fullName"] = "Amit Malhotra";

4. Use ECMAScript 5 defineProperty with accessor (get; set;) descriptor

Object.defineProperty(employee, 'fullName',
 {
 get: function() {
 return this.name.first + ' ' + this.name.last;
 },
 set: function (value){
 var nameParts = value.split(' ');
 this.name.first = nameParts[0];
 this.name.last = nameParts[1];
 }
});
 
employee.fullName = 'Amit Malhotra'
 
console.log(employee.name.first); // OUT: Amit

5. Use ECMAScript 5 defineProperty with property descriptor

Object.defineProperty(employee, 'fullName', {
 value: 'Amit Malhotra',
 writable: true,
 enumerable: true,
 configurable: true
});

What is Property Descriptor after all?

In JavaScript, you can define a metadata about the property. The following descriptor can be defined as writable, configurable and enumerable.

You can get the property descriptor using Object.getOwnPropertyDescriptor method.

Object.getOwnPropertyDescriptor(employee.name,'first');
 
// Out: Object
 
/* {
value: Amit
writable: true
enumerable: true
configurable: true
} */

writable – allow to change.

Object.defineProperty(employee, 'age', {writable: false});

Now if I try changing property as:

employee.age = 12

Then will throw this error:

TypeError: Cannot assign to read only property 'age' of 
object '#<Object>, Please note that it will throw an 
exception only if we use 'use strict'. Otherwise it will 
silently fail without changing the value of age to 12.

enumerable – allow to enum your property like this:

for(var propertyname in employee){
 display(propertyname + ': ' + employee[propertyname])
}

It returns name: [object Object], gender: M

If you set the enumerable to false:

Object.defineProperty(employee, 'gender', 
{enumerable: false})

 

The Object.keys(employee) will not return gender property. 
Similarly, if the Object.defineProperty(employee, 'gender',
{enumerable: true}) then it will return gender. You can 
still access gender like employee.gender, but you cannot 
see in Object.keys(employee)

configurable – That you can change some property descriptor

Object.defineProperty(employee,'age', {configurable: false})

Now you cannot change the property descriptor enumerable, configurable, or delete age. However, you can change writable.

 

Validate JSON response with URLs | Scripting Postman

I have been in a situation with an API url testing with the postman, where the server response has got a collection of URLs and I want to assure that these URLs are active i.e. Http OK.

To achieve this objective, I have to do the following:

  1. Call API, and store url result
  2. Call each URL and assert

Let us go one by one.

Call API, and Store URL result.
(PS: Instead of making an API call, which will return urls, I am faking my first API call 
with www.google.com, and have coding urls).
  • Open Postman and create a folder called “ValidateResponseURL”
  • Create a postman script, named as “get-contents”. It will call your API. For this demo, I am calling  www.google.com
  • Go to tests tab, and check that the response code is 200 for “GET google.com”
  • Store a collection of urls into an environment variable using postmant.setEnvironmentVariable(“…”)
  • Please note that, instead of storing url collection as it is, you need to store the first element into a separate environment variable, so that you can make a decision if there is any result from the server. In addition, it will also help you to use this dynamic url in the next step.This is how the “get-contents” step looks like in my machine.
Call each URL and assert
  • Now if you run the first postman step and check local variable, you will find the two environment variables “testurl” and “testurls”
  • Create an another postman step, named as “validate-urls”
  • Select a “Get” verb, and use “testurl” environment variable i.e. {{testurl}} as your url.
  • Now go to the tests tab of your postman step, and validate that the response code is 200.
  • Fetch a next url from “testurls” environment variable, and execute “validate-urls” step again.
  • When there is nothing left in the “testurls” collection, clear environment variables.Your script should look something like this:

Once everything is settled, you can now execute the same using Runner and you will find the result as follows:

As you can see in the result that my all websites are alive and responding with Http OK response code i.e. (200).

Thats all folks!

Namaste.

References:

“LOOPS AND DYNAMIC VARIABLES IN POSTMAN: PART 2”, https://thisendout.com/2017/02/22/loops-dynamic-variables-postman-pt2/

“Branching and Looping”, https://www.getpostman.com/docs/postman/scripts/branching_and_looping

“Test script” , https://www.getpostman.com/docs/postman/scripts/test_scripts

 

Hangfire

What is Hangfire?

The Hangfire is an open-source .net package. It allows you to run scheduled jobs with limited amount of administrative cost. Just like Windows Scheduler, Windows Service deployment is not easy, but with the help of Hangfire you can run different types of background jobs such as one time jobs (aka fire and forget), recurring jobs.

Hangfire also provides you a dashboard that represent various information such as job status report, graph, exception details etc…

How to use Hangfire?

There are many good articles on how to use and setup Hangfire. However, I suggest you to read this book from the Author: https://media.readthedocs.org/pdf/hangfire/latest/hangfire.pdf

Extra Bit

Since I have successfully implemented the same in my job, I would like to preserve my learning in this blog, along with my good looking sketch notes.

Take Away:

  • If you are planning to use for an Enterprise Platform, I suggest you to buy Hangfire Pro version, which comes with dedicated support, performance counter and other improved benefits such as Redis database support.
  • Hangfire logs a lot. Hence, I suggest you to either implement your own LogProvider for the Hangfire or if you are using a log framework such as NUnit then don’t forget to set a filter on severity level.
  • If you are using Hangfire with the Microsoft SQL Server then you might want to assess the default polling time, which is every 15 seconds.
  • By default Hangfire dashboard is accessible for localhost. You can enable or disable for production, but don’t forget to set some sort of an Authentication mechanism. The good thing is, if you don’t want Windows or Basic Authentication, you can provide your own implementation.
  • If you can afford to have a separate Hangfire database, then please create a dedicated database for your Hangfire instance. It will give you an opportunity to scale, and share the same Hangfire instance with many other projects. Otherwise, you can stick to a separate database schema.
  • Hangfire is awesome because you don’t need any server access like in the case of Windows Scheduler or Windows Services.

Like I said before you can use this sketch note for your reference.

Namaste!

 

My first Sketchnotes on “The Sketchnote Handbook”

Ever since I got to know about “The Sketchnote Handbook“, I wanted to read it. The main reason of this curiosity is because there is a belief in me, which has been reflected in this book. The belief of communicating through the Visuals. What I mean with Visuals? It means global communication, which involves freedom to innovate, design, and being not restricted by any grammar, teacher, or a rule developed by so called over intellectuals. It is about communicating with anyone, and reflecting your understanding on the topic using icons, icons and random text.

English is a language not a measure of your intelligence

It did not take much time, may be a week, to read this book. As I relearned about how to give an importance of basic design techniques, in this book, I decided to keep a reflection of my understanding using sketch notes.

These two pictures speak about the my understanding with the topic that I studied through this book.

Page 2
Page 2

I hope you will use the same for your reference.

Please don’t think that you are not good at Drawing. If you need any motivation then please look at this picture of my daughter. Just like her, I am sure you were able to draw during your childhood.

Source of Motivation - Children

Once again, it does not matter how bad or good you are in Sketching or English, your focus should be on just sketch sketch sketch and speak your knowledge.

Namaste!

 

Debug Postman

Recently, I came across a situation when I wanted to see the result of console.log written as a part of Postman script.

I could not see any outgoing call or console logs in a console of my chrome.

After a bit of research it is understood that there is a separate way of opening a console screen of a chrome app package.

To enable this feature you need to type chrome://flags/#debug-packed-apps in the URL bar in your Chrome browser window:

Once it is enabled, restart your chrome. Now you can right click on the Postman app, and inspect.

Tada! You can now view console logs and any network calls going out of the Postman.

Browsemate – Search made easy in your open tabs, bookmark and history

Have you ever been in any situation, when you wanted to search for open – tab within your chrome windows or you are facing problem in finding the website you had visited earlier! Then this plugin is the correct choice for you.

With the help of this plugin you can search for a link in your open tabs, saved bookmarks and even your browser history.

You can search by page title, or a URL/link.

How to use it?

We have provided you the Browsemate search in your browser address bar or you can use this feature through a popup window, by pressing an icon on your browse right top corner.

Address Bar:

Type “bm <search criteria>” in your address bar and it will make all the similar links visible.

Popup Windows:

Click on browsemate icon, presented next to your address bar, and then type your search criteria. You can even use arrow keys.

 

 

Where is my postgres.server start and stop command for mac?

Are you struggling shutting down your postgres ?

You are not alone. It took me only 30 minutes to find the the way out.

I know that I will forget the same in the future, or anyone else having the same question then you must read this.

Open Terminal command and run:

> vi ~/.bash_profile

copy and paste this command:

> alias postgres.server="sudo -u postgres /Library/PostgreSQL/9.4/bin/pg_ctl -D /Library/PostgreSQL/9.4/data"

PS: replace 9.4 with the PostgreSQL version that you are running.

Reload bash_profile

> source ~/.bash_profile

Now you should be able to command the following:

> postgres.server start

or

> postgres.server stop
PS: You may need to enter admin password as you are starting or shutting down the sever for all user (hopefully its only you for your machine :-) ).

Docker commands

Create docker:

> docker run -d -P --name jenkins-master -v /Users/codebased/docker:/jenkins-data jenkins

To start/restart/kill the existing docker by name

> docker start/restart/kill jenkins-master

==========================================

It will get you a list of volumes that your containers are referring to.

> docker volume list

If you want to access the docker file system as a root user.

> docker exec -it --user root <containerid/name> bash

By default the vim is not present in docker. you can install with these two command:

> apt-get update
> apt-get install vim

 

Build Android – Continuous Integration with Jenkins and Docker

header_image

This tutorial assumes that you have Jenkins in the docker. You can read about installing the same here.

 

Once the jenkins instance, named jenkins-master, is installed go to the root bash i.e. command prompt for your container.

e.g. docker exec -it --user root jenkins-master bash

From the bash command run the following:

> cd /opt

Know the sdk version and download:

> wget http://dl.google.com/android/android-sdk_r24.0.1-linux.tgz

unzip file:

> tar zxvf <filename of the just downloaded file>

You can now remove the file you just downloaded:

rm <filename of the just downloaded file>

Now some environment variables are required to be set.

vi /etc/profile.d/android.sh

——————————————————–
By default the vim is not present in docker
you need to install by the following

apt-get update
apt-get install vim
——————————————————-

Add the following lines:

export ANDROID_HOME="/opt/android-sdk-linux"
export PATH="$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools:$PATH"

Then reload the file:

source /etc/profile

Now you should be able to call android from the command.

screen-shot-2016-11-05-at-3-54-19-pm

First list the available android sdk and platform tools:

android list sdk --all --extended

Get the item serial number from output and run:

> android update sdk -u -a -t <serial number>

Replace <serial number> for required: platform version,  android support library and sdk version.

Check your android gradle file for the required version.

For the Android SDK to be accessible by Jenkins, execute the following:

> chmod -R 755 /opt/android-sdk-linux

If you get this error
Cannot run program “/usr/local/android-sdk-linux/build-tools/19.0.3/aapt”: error=2, No such file or directory

then run this command: 

> apt-get install lib32stdc++6 lib32z1

 

All set and now reboot your container: 

docker restart CONTAINERNAME/ID

 If everything is done correctly, you should be able to set the gradle task and generate android apk/jar/aar :-).

screen-shot-2016-11-05-at-3-59-07-pm
Reference: https://www.digitalocean.com/community/tutorials/how-to-build-android-apps-with-jenkins