Javascript inheritance implementation using prototypes

This is a fully functional implementation with no weird back references or unwanted functionality. I’ve gone through many different implementations before settling on this. Keep in mind that I had some constraints you may not have and could not use the new ECMA 2015 syntax that introduced the “class” keyword among many other great enhancements.

The Javascript world is full of surprises and tricks that could leave your head spinning for days especially if you are coming from a world of structure and order such as Java or C#.

Object inheritance is complicated and messy, there are several ways of implementing it and different flavor for each creating a huge web of complicated code to choose from.

There are new developments and methods that will definitely improve this situation but if you are forced to stay within the bounds of older implementations like I was while implementing Jurassic interpreter within C# code, the following will get the job done.


These are my requirements:

  1. Parent “class” with properties and methods and a parameterless constructor.
  2. Child “class” with own properties and methods and a parameterless constructor.
  3. Child class will inherit Parent’s properties
  4. Child class will inherit Parent’s methods
  5. You can add methods to either Parent or Child even after objects were created.
  6. Adding method to parent will also make that same method available to all children automatically
  7. There are no unwanted references maintained between the Parent and Child definitions or any of the object instantiated using them. (This is often an issue with some of the other ways you can attempt inheritance in javascript)


We’ll start by defining constructors that will describe the objects. You will notice Object.assign(this, new Grandparent()); call, that call creates an instance of the base object similar to a super or base call in other languages. I’ve tried using the “call” function; but couldn’t get it working in my environment.

var Grandparent = function() { = 'I am the grandfather';	
	this.age = 70;
	this.likesCoffee = true,
	this.items = {
		house: {
			bedrooms: 7
	this.getItems = function() {
		return this.items;

var Parent = function() {
	Object.assign(this, new Grandparent()); // Copy properties from Granparent, Requirement #3 = 'I am the parent.';
	this.age = 40;
	this.secretLanguage = function() {
		return 'the secret language';

var Child = function() {
	Object.assign(this, new Parent()); // Copy properties from Parent, Requirement #3 = 'I am the child.';
	this.age = 10;

The next step is to link the prototypes so that any new functions added to the base class will propagate down the inheritance hierarchy. Note that by linking Parent to Grandparent and Child to Parent the child will also be linked to Grandparent by default.

Parent.prototype = Object.create(Grandparent.prototype);
Child.prototype = Object.create(Parent.prototype);

To illustrate that we can add a new prototype method to the Grandparent that will then be available to both Parent and Child

Grandparent.prototype.getAge = function() {
	return this.age + ' years';

Full working example

Below is a complete example with comments. It addresses all of the requirements stated before.

// Define the "constructors", this is somewhat similar to defining a class
// Requirements #1 and #2

var Grandparent = function() { = 'I am the grandfather';	
	this.age = 70;
	this.likesCoffee = true,
	this.items = {
		house: {
			bedrooms: 7
	this.getItems = function() {
		return this.items;

var Parent = function() {
	Object.assign(this, new Grandparent()); // Copy properties from Granparent, Requirement #3 = 'I am the parent.';
	this.age = 40;
	this.secretLanguage = function() {
		return 'the secret language';

// Link the prototype
// This will give access to current and future methods of the Grandparent

Parent.prototype = Object.create(Grandparent.prototype);

var Child = function() {
	Object.assign(this, new Parent()); // Copy properties from Parent, Requirement #3 = 'I am the child.';
	this.age = 10;

// Link the prototype
// This will give access to current and future methods of the Parent and Grandparent

Child.prototype = Object.create(Parent.prototype);

// Now we are ready to create some people

var grandpa = new Grandparent();
var dad = new Parent();
var son = new Child();

// Both dad and son should like coffee 
// Requiement #3

console.log("Dad likes coffee: ", dad.likesCoffee);
console.log("Son likes coffee: ", son.likesCoffee);

// Both dad and child have their own secretLanguage method
// but not the grandparent
// Requirement #4

console.log("Dad knows ", dad.secretLanguage());
console.log("Son knows ", son.secretLanguage());
try {
	console.log("Grandpa knows ", grandpa.secretLanguage()); // this will fail
} catch(e) {

// Now lets try to add a method to the Grandparent
// Requirement #5

Grandparent.prototype.getAge = function() {
	return this.age + ' years';

// Check if the method is in fact available at the different levels.
// Requirement #6

console.log("Grandpa's age: ", grandpa.getAge());
console.log("Dad's age: ", dad.getAge());
console.log("Son's age: ", son.getAge()); 

// Now how about a method that was defined on Grandparent before
// we declared Parent and Child
// The grandparent has a large house so they all live together

console.log("Son's house: ", son.getItems().house);

// Lets say that the dad decides to move out along with his son
// into a new smaller home. (One would say it's about time)
// We could update the house property to an entirely new
// object like so:
/* = {
		bedrooms: 3
// But since there should be no "back" references we can also
// just update the number of bedroom directly = 3;
console.log("Dad's house: ", dad.getItems().house);

// This should not affect grandpa's living situation
// Requirement #7

console.log("Grandpa's house: ", grandpa.getItems().house);

// But we do want to keep son's house in sync with the dad from now on
// so let's create a reference =
console.log("Son's house: ", son.getItems().house);


The script should produce the following output:

Dad likes coffee: true
Son likes coffee: true
Dad knows the secret language
Son knows the secret language
TypeError: grandpa.secretLanguage is not a function
at :60:40
Grandpa’s age: 70 years
Dad’s age: 40 years
Son’s age: 10 years
Son’s house: {bedrooms: 7}
Dad’s house: {bedrooms: 3}
Grandpa’s house: {bedrooms: 7}
Son’s house: {bedrooms: 3}

Automating letsencrypt certificate renewal with cron

Letsencrypt allows you to install free SSL certificates on your site. The certificates expire after 3 months and they need to be renewed to avoid certificate errors.

Depending on how you install letsencrypt, and once you configure the certificates on the site, you will want to setup automatic renewal so you don’t have to manually check and renew.

You can setup automated renewals using cron scheduling tool on linux and the following steps:

1. Sudo to root user:
sudo su –

2. Edit crontab file:
crontab -e

3. Add the following line:
00 9 * * 6 /etc/letsencrypt/.certbot-auto renew –no-random-sleep-on-renew –renew-hook ‘/sbin/service httpd restart’ > /var/log/cert_renew.log 2>&1

Let’s break down the entry to see what some of the elements mean:

00 9 * * 6
This is the schedule part, we are going to run every Saturday (day 6) at 9:00am

/etc/letsencrypt/.certbot-auto renew –no-random-sleep-on-renew
This executes the renew command and specifies that there should be no random sleep delay because of the non-interactive (no user input) mode

–renew-hook ‘/sbin/service httpd restart’
The renew hook allows running of a command upon certificate renewal, so only if the certificate or certificates were expired and had to be renewed

> /var/log/cert_renew.log 2>&1
Finally, we are redirecting the output of the command to the /var/log/cert_renew.log file.

You can also use a similar line for testing the command, the below uses the “–force-renewal” flag that will renew all certificates even if they are not expired yet:

51 21 * * * /etc/letsencrypt/.ertbot-auto renew –force-renewal –no-random-sleep-on-renew –renew-hook ‘/sbin/service httpd restart’ > /var/log/cert_renew.log 2>&1

How to display the git version on your site

Here is a quick guide on how to automatically update the build version of your site directly from git.
This approach leverages the “hook” functionality to get the build hash after a commit.

Versioning files is a must for any developer and git version control system is one of the de facto choices for that job. It’s my personal favorite as well. You can learn more about git here.

Go into your projects .git folder, then hooks. You should see a list of sample hooks already there.
Create a new one called “post-commit” (note there is no file extension).

Add the following content:

# Get the Git Revision and write make available to the application
# This will write the short commit hash to the version-commit.php file.
version=$(git rev-parse --short HEAD)
echo "" > version-commit.php

Once you “include” the version-commit.php file the VERSION_COMMIT constant will now be available to display anywhere in your site. For example:

$versionMajor = '1.0';
$version = $versionMajor.'.'.VERSION_COMMIT;
echo $version;

Now you are probably thinking that this would cause the project to show new changes because of version-commit.php file change.

For that we need to update “.gitignore” file in the project root folder:

# Don't version the version file

One thing to note is that the version-commit.php file will not exist for a cloned (checked out) repository until a new change is committed, since that file is not committed with the code to avoid an endless loop of change/commit cycle.

I am yet to find a clean and simple way around that but this problem is a small price to pay for some useful automation.

WooCommerce default to free shipping or legacy free shipping

Recent WooCommerce updates (starting with 2.6.0) introduced the concept of shipping zones.  You have the option to configure Shipping Zones, which will provide the standard selections like Flat Rate, Free Shipping and Local Pickup.  

In the meantime however, the existing shipping methods will be renamed with a legacy "legacy_" prefix and that can cause some of the shipping customizations to no longer work. One of those is the snippet provided by WooCommerce used to hide all other shipping methods when free shipping is available. The code relies on the shipping method using method_id of free_shipping and no longer works since the method_id has changed to legacy_free_shipping.

To support the legacy_free_shipping shipping method but also be ready for when your regions are configured you can use the following modified code (This needs to be added/replaced in functions.php).

function my_hide_shipping_when_free_is_available( $rates ) {
    $free = array();
    $legacyFree = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
        if ( 'legacy_free_shipping' === $rate->method_id ) {
            $legacyFree[ $rate_id ] = $rate;
    return ! empty( $free ) ? $free : (!empty($legacyFree) ? $legacyFree : $rates);
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );        

The original code is here:

Secure EC2 Apache server with Let’s Encrypt

Having an SSL secured website is no longer just a preference for sites handling sensitive data but is a necessity for all websites. There are many good reasons to secure your site even if only to improve the ranking in Google search.

Let’s Encrypt is a Certificate Authority organization providing free SSL certificates. The project is supported by many large technology organizations with the goal of securing all websites on the web.

The certificates are free and are valid for three months at a time.

A few assumptions before proceeding:

-You have installed the AMI Linux on the EC2 instance -You have installed httpd (Apache) using standard options -Your installation is done using the standard (out-of-the-box) ec2-user -You have a DNS entry to point your domain name to the EC2 instance

  1. Start apache if not already started sudo service httpd start
  2. Update all installed packages sudo yum update -y
  3. Install mod_ssl apache module sudo yum install -y mod24_ssl
  4. Bounce apache sudo service httpd restart The server will now work with HTTPS but using an untrusted certificate that will cause a warning to be displayed in the browser.
  5. Install git. Git is needed to download the letsencrypt code. sudo yum install git
  6. Clone the letsencrypt repository (download) git clone
  7. Run the letsencrypt utility to generate and install certificate files. Note the following parameters: -d YOUR_DOMAIN – This is the domain name. You have to have DNS configured so your domain points to the EC2 instance using the public IP. --webroot-path – This path should match your DocumentRoot path in httpd.conf. By default it’s /var/www/html --email YOUR_EMAIL – This should be the email address you want to use for notifications related to letsencrypt --debug – Necessary due to experimental AMI (Amazon Linux) support. Full command: ~/letsencrypt/letsencrypt-auto certonly --renew-by-default -d YOUR_DOMAIN --authenticator webroot --webroot-path /var/www/html --email YOUR_EMAIL --agree-tos --debug
  8. A successful run should result in a message similar to the following. Note the path to the certificate files: /etc/letsencrypt/live/YOUR_DOMAIN
    The path will be needed to finish apache configuration.
 - Congratulations! Your certificate and chain have been saved at
   /etc/letsencrypt/live/YOUR_DOMAIN/fullchain.pem. Your cert
   will expire on 2016-10-15. To obtain a new or tweaked version of
   this certificate in the future, simply run letsencrypt-auto again.
   To non-interactively renew *all* of your certificates, run
   "letsencrypt-auto renew"
 - If you lose your account credentials, you can recover through
   e-mails sent to YOUR_EMAIL.
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:
   Donating to EFF:          
  1. Edit the Apache SSL configuration file. The file came with the mod_ssl installation and is loaded automatically by apache. sudo vi /etc/httpd/conf.g/ssl.conf
  2. Update the following entries in the file
SSLProtocol-SSLv2 -SSLv3 +TLSv1 +TLSv1.1 +TLSv1.2
  1. You should also redirect all traffic to HTTPS. To do so, edit the httpd.conf file sudo vi /etc/httpd/conf/httpd.conf
  2. Add the following section at the end of the file

SSL Redirect

RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^/(.*) https://%{SERVER_NAME}/$1 [R,L]

  1. Bounce apache sudo service httpd restart

The site should now show as secured in the browser. Keep in mind that the certificate will expire in 3 months. I will share steps on how to configure automatic renewal in another post.


Mozilla SSL Configuration Generator

Amazon guide to installing LAMP Web Server on Amazon Linux

Amazon guide to enabling SSL

Amazon guide to installing LAMP Web Server on Amazon Linux

Amazon guide to enabling SSL

Retrofitting PHP code to use namespaces

Using namespaces in PHP can be bit more work than it appears and in some cases will require some mass search/replace to be performed.   There is one particular scenario where that process becomes unnecessarily tedious and i will show you how to make it less so.

Quick Intro to Namespaces

Without namespaces every one of your classes must use a unique name.  Using namespaces is a no-brainer for someone from a Java background where they are called packages and you pretty much can’t code without them.  But in php world you can write entire applications without ever touching the subject. Namespaces provide a way to group Classes into logical groups or modules.

Here are two PersonalBio classes without using namespaces. Since the class names have to be unique the naming gets messy.

Same class definitions using namespaces would look like this

Using namespaces allows the class names to be more generic and short. It also prevents conflicts with other libraries and built in classes.
A good example of this would be a class called Directory. Since Directory is a built-in php class you cannot have your own without specifying a namespace:

This will not work due to a conflict with an existing php class:

Same class is ok within a namespace:

The Retrofit Process
The easiest way to retrofit the existing code is to use en editor such as Notepad++ and perform regular expression replacements.
For instance, when referencing classes that don't have a namespace from a class with a namespace you will be faced with a problem of having to prefix all those references with a backslash.  There is currently no other easy reliable way to do this:

Use the following search and replace patterns:
Replace With:
The "\b" determines the word boundary and the "|" allows you to replace multiple classes at a time.  This comes in very handy when there are dozens.
This is the result:

<?php namespace MyApp; class Test { $instance1 = new \FirstClassWithoutNamespace(); $instance2 = new \SecondClassWithoutNamespace(); } You can do similar replacements for classes using namespaces: Search: (\bFirstClass\b|\bSecondClass\b) Replace With: \\SomeOtherNamespace\\$1 And the result:

First steps with PostCSS

PostCSS is getting a lot of attention lately and I decided to give it a try. Post-processing may seem counter intuitive especially if you are used to tools like SASS and LESS, but will make more sense the more time you spend tinkering.

With a post-processor you can define global styles that can then be transformed into specific rules for different components of the web application. This is really quite powerful and allows for creating of a simple set of styles that can then be targeted at specific components.  One use would be to have a branding stylesheet that can be applied to different plugins or products.

The concept is somewhat similar to what you can do using pre-processors (eg. Bootstrap and variables) but way more flexible and arguably much cleaner as well.  As the base stylesheet could remain unchanged and processing code is added with each additional integration.

Of course, that is only one way to utilize the functionality but the possibilities are countless.
There is a lot of potential here and for workflows that are clean and reusable so make sure to give PostCSS a try. Here are some steps to get up and running quickly:

  1. Install node.js (if you haven’t already)
  2. Create a folder for the test project.
  3. Access command line and go into the folder.
  4. Run the following commands to install the CLI version of the PostCSS package as well as the Autoprefixer plugin. (There are several other PostCSS plugins available and you also have the ability to create your own – the main strength of PostCSS).

The CLI version is a wrapper around the regular PostCSS package and allows you to run PostCSS without any additional build packages. Good for getting to know how it works.

npm install postcss-cli
npm install autoprefixer

The commands will install the packages under node_modules directory created in your current directory.

  1. Create a test file called test.css with the following content.
.transparent {
  opacity: 0;
  transition: opacity 1s;
  1. Create an options file called test.json with PostCSS and Autoprefixer options. This allows you to configure parameters for the autoprefixer plugin. In this case a query for supported browsers (see:
  "use": ["autoprefixer"],
  "autoprefixer": {
    "browsers": "> 5%"
  1. Execute the following command to compile the css. result.css will contain the output.
postcss -c test.json -o result.css test.css

You should see that the autoprefixer plugin added browser specific prefixes.

Styling nested elements with LESS

LESS is a great tool for removing the tediousness out of CSS styling by allowing nested selectors and use of variables.
But there is much more to the language allowing for more complex logic to be embedded. One of the great features of the language is the ability to loop and create styles recursively.

A good practical use for this functionality is to style a comments section:

See the Pen Styling nested elements with LESS by Marcin Jackowiak (@marcinjackowiak) on CodePen.

Below is the basic LESS code will generate CSS that varies the div background color depending on how deep the element is in the DOM hierarchy.
It is a prime example of something that could be a nightmare to maintain directly in the CSS stylesheet.

#namespace {
  .test(@i,@x) {
    div {
      background-color: lighten(red, @i*(50/@x));

  .recursive(@x; @i:0) when (@i <= @x) {
      div {
        .recursive(@x; (@i+1));

div {
  width: 200px;
  height: 200px;
  padding: 20px;
  border: 1px solid #888;

& { #namespace > .recursive(5); }

What it generates is a nice gradient of red that will lighten the deeper you go.
The following formula will lighten the color by 50% with each level. To create a smoother transition simply lower the

      background-color: lighten(red, @i*(50/@x));

The argument in the .recursive mixin allows you to specify the depth to which the styles will be generated.

& { #namespace > .recursive(5); }

The resulting CSS is as follows.

div {
  width: 200px;
  height: 200px;
  padding: 20px;
  border: 1px solid #888;
div {
  background-color: #ff0000;
div div {
  background-color: #ff3333;
div div div {
  background-color: #ff6666;
div div div div {
  background-color: #ff9999;
div div div div div {
  background-color: #ffcccc;
div div div div div div {
  background-color: #ffffff;

Ajax calls in WordPress

Adding Ajax functionality to your theme or plugin code can be a bit challenging. I will distill the many articles, tips and forums i’ve read on how to do this and provide straightforward workflow you can use.

The consensus is that the safest way to handle ajax calls in wordpress is through the use of the built-in capability provided by admin-ajax.php and so that is how we will proceed.

The sequence of steps that have to occur are as follows.

1. Register, enqueue and localize a javascript file.

This one may seem confusing but localizing in this case is simply a way of injecting the info we will need on client side.  This .js file can be empty but has to exist.

wp_enqueue_script( 'my-ajax', get_stylesheet_directory_uri().'/assets/js/ajax.js');

wp_localize_script( 'my-ajax', 
                        'ajaxurl' => admin_url( 'admin-ajax.php' ),
                        'nonce' => wp_create_nonce( 'my-ajax-nonce' ),

In the example above MyAjaxObject is how you will get the ajaxurl and the nonce in your javascript code. For example:

alert(MyAjaxObject.ajaxurl); // Display ajaxurl value
alert(MyAjaxObject.nonce); // Display the nonce

2. Create a php class to hold data for all your ajax calls.

This is not absolutely necessary but will make it easier to maintain a common pattern across all of your ajax code.

Create a new php file to hold the class, for example my_ajax_response_class.php

class MyAjaxResponse {

public $message;
public $html;
public $exception;


You add any variables you feel you might need to use i prefer the above.

Note: you do not need a success indicator in this class, that will be automatically provided by wordpress’ wp_send_json_success and wp_send_json_error methods.

3. Create and register the php function to handle the call and respond.

Here you will create a function and register it either inside of functions.php file or any other php file you import in functions.php.

The function will accept any incoming parameters, perform some operations and return a JSON formatted response

    function monday_fail() {
        $resp = new MyAjaxResponse();

        if(!wp_verify_nonce($nonce, 'my-ajax-nonce')) {

        $monday = 1;
        $jdd = jddayofweek();
        switch($jdd) {
            case $monday:
                $resp->;message = 'It\'s a monday.';
                $resp->;html = 'It\'s not a monday.';                

To register this function you will need to use one of the following methods.  The first requires a logged-in user while the second does not and is more suited for front-end calls.

There are some additional notes on how exactly those two differ in here: (go to the Ajax on the Viewer-Facing Side section)

  1. wp_ajax_{some_name}
  2. wp_ajax_nopriv_{some_name}

In my examples I use the wp_ajax_{some_name} action so the user does have to be logged in.

    if(is_admin()) {
        add_action('wp_ajax_monday-fail', 'monday_fail');        

A nonce (form of a security token) will be used for all calls to ensure the requests are coming from where we expect.

4. Make the call from javascript and handle the response.

In this final piece of the puzzle you will create the code that makes the calls and handles the response.  I always choose to use jQuery for this purpose so here it is.

    jQuery(document).ready(function ($) { 

        function create_directory(newName) {
                type       : "POST",
                data       : {
                              action: 'monday-fail', 
                              nonce : MyAjaxObject.nonce                              
                dataType   : "JSON",
                url        : MyAjaxObject.ajaxurl,
                success    : function(data){

                    if(data.success) {
                    } else {
                       alert(; // display the returned message

                error     : function(jqXHR, textStatus, errorThrown) {
                    alert('Unable to check what day it is.');
                    console.log(jqXHR + " :: " + textStatus + " :: " + errorThrown);


A few notes on the above code:

The above code will typically go into the head section of the page, inside of a script tag.

The dataType is set to JSON since that’s how we will receive our response.

Url is set using the object we created by localizing our script in Step 1.

To refer to our MyAjaxResponse object from Step 2 we use, that’s how the wordpress function embeds it.

As part of the data we send to the function is action, that has to match {some_name} name used when you registered the function in Step 3.

The other variable: nonce, is generated through localization in Step 1.


wp_send_json_succes and wp_send_json_error automatically handle the response portion of the logic but if you choose not to use them make sure to die(); after sending the response to the client otherwise a 0 or other junk will be appended to the response on the client side.