Javascript inheritance best example

Thanks to david shariff for his post.

This post is only a copy of his post for my reference.

JavaScript Inheritance Patterns

In this post, I am going to introduce to you 3 different ways of how you can implement inheritance in JavaScript. You will see inheritance implemented in languages such as Java by allowing a class to inherit state and behavior from a superclass, where each superclass can have many subclasses.

This means that in Java an object is an instance of a class, which can inherit other classes. Now in JavaScript, being prototypal by nature, an object can inherit from an object.

For the rest of this post, I will introduce the Pseudoclassical, Functional and Prototypal inheritance patterns in JavaScript.

Pseudoclassical pattern

The Pseudoclassical pattern tries to replicate inheritance in a way that is familiar to those who come from a Java or C like background. By using Pseudoclassical inheritance, we attempt to recreate classic programming language’s behavior by using class wide inheritance and where objects are instances of those classes.

A pattern which uses a constructor function and the new operator, combined with a prototype added to the constructor is said to be Pseudoclassical.

In JavaScript, one way to do this inheritance is:

  1. Invoke a constructor function.
  2. Point a child’s prototype to the parent’s prototype for inheritance to occur.
/**
 * Point a child's prototype to a parent's prototype
 **/
var extendObj = function(childObj, parentObj) {
    childObj.prototype = parentObj.prototype;
};

// base human object
var Human = function() {};
// inhertiable attributes / methods
Human.prototype = {
    name: '',
    gender: '',
    planetOfBirth: 'Earth',
    sayGender: function () {
        alert(this.name + ' says my gender is ' + this.gender);
    },
    sayPlanet: function () {
        alert(this.name + ' was born on ' + this.planetOfBirth);
    }
};

// male
var Male = function (name) {
    this.gender = 'Male';
    this.name = 'David';
};
// inherits human
extendObj(Male, Human);

// female
var Female = function (name) {
    this.name = name;
    this.gender = 'Female';
};
// inherits human
extendObj(Female, Human);

// new instances
var david = new Male('David');
var jane = new Female('Jane');

david.sayGender(); // David says my gender is Male
jane.sayGender(); // Jane says my gender is Female

Male.prototype.planetOfBirth = 'Mars';
david.sayPlanet(); // David was born on Mars
jane.sayPlanet(); // Jane was born on Mars

As expected, we have achieved inheritance in a Pseudoclassical manner, however, this solution has a problem. If you look at the last line, you will see the alert says Jane was born on Mars, but what we really want it to say is Jane was born on Earth. The reason for this is the Male prototype was changed to “Mars”.

Given the direct link between the Male and Human prototype, if Humanhas many children inheriting from it, any change on a child’s prototype properties will affect Human, and thus all children inheriting from Human. Changing a child’s prototype should not affect other children inheriting from the same parent. The reason for this is because JavaScript passes objects by reference, not by value, meaning all children of Human inherit changes occurred on other children’s prototypes.

childObj.prototype = parentObj.prototype does give us inheritance. However, if you want to fix the issue above, you need to replace theextendObj function to take the child’s prototype and link it to a temporary object, whose prototype is the parent object’s prototype. In this way, by creating a temporary “middle” object, you allow the temporary object to be empty and inherit its properties from Human.

By doing this, you have solved the pass by reference issue with a new instance of an empty object, which still inherits from the parent, but is not affected by other children.

To understand this clearly, the image below shows the flow of theextendObj function.

classical inheritance

Now, if you ran the same code again, but with the changes in extendObjbelow, you would see “Jane was born on Earth” was alerted.

/**
 * Create a new constructor function, whose prototype is the parent object's prototype.
 * Set the child's prototype to the newly created constructor function.
 **/
var extendObj = function(childObj, parentObj) {
    var tmpObj = function () {}
    tmpObj.prototype = parentObj.prototype;
    childObj.prototype = new tmpObj();
    childObj.prototype.constructor = childObj;
};

// base human object
var Human = function () {};
// inhertiable attributes / methods
Human.prototype = {
    name: '',
    gender: '',
    planetOfBirth: 'Earth',
    sayGender: function () {
        alert(this.name + ' says my gender is ' + this.gender);
    },
    sayPlanet: function () {
        alert(this.name + ' was born on ' + this.planetOfBirth);
    }
};

// male
var Male = function (name) {
    this.gender = 'Male';
    this.name = 'David';
};
// inherits human
extendObj(Male, Human);

// female
var Female = function (name) {
    this.name = name;
    this.gender = 'Female';
};
// inherits human
extendObj(Female, Human);

// new instances
var david = new Male('David');
var jane = new Female('Jane');

david.sayGender(); // David says my gender is Male
jane.sayGender(); // Jane says my gender is Female

Male.prototype.planetOfBirth = 'Mars';
david.sayPlanet(); // David was born on Mars
jane.sayPlanet(); // Jane was born on Earth

Functional pattern

Another pattern you can use to achieve inheritance in JavaScript is byDouglas Crockford, called Functional inheritance. This pattern allows one object to inherit from another, take the result and augment it at the child level to achieve inheritance. What this really means, is you create an object as your parent, pass the child object to the parent to inherit / apply its properties, and return the resulting object back to the child, who can then augment its own properties to the object returned from the parent.

Below is the same example used above to explain Pseudoclassical inheritance, but written in a functional nature.

var human = function(name) {
    var that = {};

    that.name = name || '';
    that.gender = '';
    that.planetOfBirth = 'Earth';
    that.sayGender = function () {
        alert(that.name + ' says my gender is ' + that.gender);
    };
    that.sayPlanet = function () {
        alert(that.name + ' was born on ' + that.planetOfBirth);
    };

    return that;
}

var male = function (name) {
    var that = human(name);
    that.gender = 'Male';
    return that;
}

var female = function (name) {
    var that = human(name);
    that.gender = 'Female';
    return that;
}

var david = male('David');
var jane = female('Jane');

david.sayGender(); // David says my gender is Male
jane.sayGender(); // Jane says my gender is Female

david.planetOfBirth = 'Mars';
david.sayPlanet(); // David was born on Mars
jane.sayPlanet(); // Jane was born on Earth

As you can see by using this pattern, there is no need to use the prototype chain, constructors or the “new” keyword. Functional inheritance achieves this by passing a unique object around every time an instance of the function is called.

This however, has a downside for performance because each object is unique, meaning each function call creates a new object, so the JavaScript interpreter has to assign new memory to the function in order to recompile everything inside of it as unique again.

There are also benefits to this approach, as the closures of each function allow for good use of public and private methods / attributes. Let’s take this code for example, which shows a parent class of vehicle and children classes of motorbike and boat.

var vehicle = function(attrs) {
    var _privateObj = {
        hasEngine: true
    },
    that = {};

    that.name = attrs.name || null;
    that.engineSize = attrs.engineSize || null;
    that.hasEngine = function () {
        alert('This ' + that.name + ' has an engine: ' + _privateObj.hasEngine);
    };

    return that;
}

var motorbike = function () {

    // private
    var _privateObj = {
        numWheels: 2
    },

    // inherit
    that = vehicle({
        name: 'Motorbike',
        engineSize: 'Small'
    });

    // public
    that.totalNumWheels = function () {
        alert('This Motobike has ' + _privateObj.numWheels + ' wheels');
    };

    that.increaseWheels = function () {
        _privateObj.numWheels++;
    };

    return that;

};

var boat = function () {

    // inherit
    that = vehicle({
        name: 'Boat',
        engineSize: 'Large'
    });

    return that;

};

myBoat = boat();
myBoat.hasEngine(); // This Boat has an engine: true
alert(myBoat.engineSize); // Large

myMotorbike = motorbike();
myMotorbike.hasEngine(); // This Motorbike has an engine: true
myMotorbike.increaseWheels();
myMotorbike.totalNumWheels(); // This Motorbike has 3 wheels
alert(myMotorbike.engineSize); // Small

myMotorbike2 = motorbike();
myMotorbike2.totalNumWheels(); // This Motorbike has 2 wheels

myMotorbike._privateObj.numWheels = 0; // undefined
myBoat.totalNumWheels(); // undefined

You can see that it is fairly easy to provide encapsulation. The_privateObj can not be modified from outside of the object, unless exposed by a public method like increaseWheels(). Similarly, private values can also only be read when exposed by a public method, such as motorbike’s totalNumWheels() function.

Prototypal pattern

You can also implement inheritance in JavaScript using a pure prototypal approach which is more suited to the language.
As of ECMAScript 5, it is possible to create an inherited object by simply doing the following:

var male = Object.create(human);

However, support is not so good for older browsers, thankfully you can augment the Object with a create method should it not exist already, which will have the same behavior as that of ECMAScript 5.

(function () {
    'use strict';

    /***************************************************************
     * Helper functions for older browsers
     ***************************************************************/
    if (!Object.hasOwnProperty('create')) {
        Object.create = function (parentObj) {
            function tmpObj() {}
            tmpObj.prototype = parentObj;
            return new tmpObj();
        };
    }
    if (!Object.hasOwnProperty('defineProperties')) {
        Object.defineProperties = function (obj, props) {
            for (var prop in props) {
                Object.defineProperty(obj, prop, props[prop]);
            }
        };
    }
    /*************************************************************/

    var human = {
        name: '',
        gender: '',
        planetOfBirth: 'Earth',
        sayGender: function () {
            alert(this.name + ' says my gender is ' + this.gender);
        },
        sayPlanet: function () {
            alert(this.name + ' was born on ' + this.planetOfBirth);
        }
    };

    var male = Object.create(human, {
        gender: {value: 'Male'}
    });

    var female = Object.create(human, {
        gender: {value: 'Female'}
    });

    var david = Object.create(male, {
        name: {value: 'David'},
        planetOfBirth: {value: 'Mars'}
    });

    var jane = Object.create(female, {
        name: {value: 'Jane'}
    });

    david.sayGender(); // David says my gender is Male
    david.sayPlanet(); // David was born on Mars

    jane.sayGender(); // Jane says my gender is Female
    jane.sayPlanet(); // Jane was born on Earth
})();

Summary

So today we have covered 3 different ways that you can implement inheritance in JavaScript. Most people are aware of prototypes, but as we have seen today, the Pseudoclassical and Functional patterns are just as valid.

Which pattern you should use varies depending on your project, there is no real “1 fits all” solution, so you are best to choose 1 you feel is the most suitable.

Advertisements

How to read array of json objects using filters in angularjs

vm.updateProducts = [
            {productCode:’03’, locationCode: ’11’, key:’123′, newProductName: ‘Product1’},
            {productCode:’05’, locationCode: ’12’, key:’456′, newProductName: ‘Product2’},
            {productCode:’05’, locationCode: ’13’, key:’789′, newProductName: ‘Product3’},
            {productCode:’50’, locationCode: ’14’, key:’101′, newProductName: ‘Product4’},
        ];
 
 
 
function isDownSell(){
            var myProd = $filter(‘filter’)(vm.updateProducts, { productCode: vm.application.applicationProductList[0].productCode, locationCode: vm.application.applicationProductList[0].locationCode });
                    
            session.set(constants.PRODUCT_NAME, myProd[0].newProductName);
            
            
        }

when we should go for nodejs

To Say Generic,

  • is a command-line tool that can be run as a regular web server and lets one run JavaScript programs
  • utilizes the great V8 JavaScript engine
  • is very good when you need to do several things at the same time
  • is event-based so all the wonderful Ajax-like stuff can be done on the server side
  • lets us share code between the browser and the backend

Node.js is especially suited for applications where you’d like to maintain a persistent connection from the browser back to the server. Using a technique known as “long-polling”, you can write an application that sends updates to the user in real time. Doing long polling on many of the web’s giants, like Ruby on Rails or Django, would create immense load on the server, because each active client eats up one server process. This situation amounts to a tarpit attack. When you use something like Node.js, the server has no need of maintaining separate threads for each open connection.

This means you can create a browser-based chat application in Node.js that takes almost no system resources to serve a great many clients. Any time you want to do this sort of long-polling, Node.js is a great option.

Why cant we use old traditional methods in sending data like ajax,push etc etc

Sending Data

Nowadays, to send a request to a server, it is very common to use AJAX to send an XMLHTTPRequest to the server without any page reloads.

Polling

One way to solve this issue is by requesting the server periodically. This could be achieved by a simple setInterval function with an ajax call to the server every x seconds. This would be called polling, because we are constantly asking the server, ‘do you have anything new?’.

Push Technology – Event Based Programming

But what if the server wants to send the client new data that the client is interested in, but has no idea when the data would be available? This is sometimes referred to as push technology, where a server wants to send data to a client. A way to think about push technology is to only do something when there’s a reason. That is, the server will only send a data response when there’s data available.

Long Polling

Long polling is where the client requests new data from the server, but the server does not respond until there is data. In the meantime, the client has an open connection to the server and is able to accept new data once the server has it ready to send.

subscribe: function(callback) {
      var longPoll = function(){
          $.ajax({
              method: 'GET',
              url: '/messages', 
              success: function(data){
                  callback(data)
              },
              complete: function(){
                  longPoll()
              },
              timeout: 30000
          })
      }
      longPoll()
  }

When it comes to Nodejs:

On the server side, the request is then subscribed to the message bus.
In Nodejs, the message bus is built in and can be required as follows. And you’ll probably want to set max listeners to more than the default of 10.

var EventEmitter = require('events').EventEmitter  
var messageBus = new EventEmitter()  
messageBus.setMaxListeners(100)  

Subscring the request.

router.get('/messages', function(req, res){  
    var addMessageListener = function(res){
        messageBus.once('message', function(data){
            res.json(data)
        })
    }
    addMessageListener(res)
})

And so you’re wondering, when will this message bus ever fire back data to the response?
Since we have a subscriber to the event, we also need a publisher to cause an event.

To emit a message to the message bus, the client, or something else, will need to initiate a publish event.

publish: function(data) {  
    $.post('/messages', data)
}

And so the server can then emit a message to the message bus.

router.post('/messages', function(req, res){  
    messageBus.emit('message', req.body)
    res.status(200).end()
})

In this set up, you ensure that every client continually has an open connection to the server, but the server is not easily overloaded to a multitude of requests, because it puts every request/response inside a message bus to be emitted once it is ready.
This method has been widely popular due to its relatively easy set up and wide support accross all browsers.

 How does it work??
toptal-blog-1_B

A quick calculation: assuming that each thread potentially has an accompanying 2 MB of memory with it, running on a system with 8 GB of RAM puts us at a theoretical maximum of 4000 concurrent connections, plus the cost of context-switching between threads. That’s the scenario you typically deal with in traditional web-serving techniques. By avoiding all that, Node.js achieves scalability levels of over 1M concurrent connections (as a proof-of-concept).

There is, of course, the question of sharing a single thread between all clients requests, and it is a potential pitfall of writing Node.js applications. Firstly, heavy computation could choke up Node’s single thread and cause problems for all clients (more on this later) as incoming requests would be blocked until said computation was completed. Secondly, developers need to be really careful not to allow an exception bubbling up to the core (topmost) Node.js event loop, which will cause the Node.js instance to terminate (effectively crashing the program).

The technique used to avoid exceptions bubbling up to the surface is passing errors back to the caller as callback parameters (instead of throwing them, like in other environments). Even if some unhandled exception manages to bubble up, there are mutiple paradigms and tools available to monitor the Node process and perform the necessary recovery of a crashed instance (although you won’t be able to recover users’ sessions), the most common being the Forever module, or a different approach with external system toolsupstart and monit.

NPM: The Node Package Manager

When discussing Node.js, one thing that definitely should not be omitted is built-in support for package management using the NPM tool that comes by default with every Node.js installation. The idea of NPM modules is quite similar to that of Ruby Gems: a set of publicly available, reusable components, available through easy installation via an online repository, with version and dependency management.

A full list of packaged modules can be found on the NPM website https://npmjs.org/ , or accessed using the NPM CLI tool that automatically gets installed with Node.js.