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.

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.



Real Essence of HTML5

What are those? Any example??

Page load time is one of the most important aspects of the user experience. Unfortunately, troubleshooting a slow page load is not easy because there are many contributing factors. To help with this, We have Navigation timing API.

function onLoad() {
  var now = new Date().getTime();
  var page_load_time = now - performance.timing.navigationStart;
  alert("User-perceived page loading time: " + page_load_time);
}

Establishing “socket” connections between a web browser and a server using Web Sockets API..

High Resolution Time API

The High Resolution Time API provides the current time in sub-millisecond resolution and such that it is not subject to system clock skew or adjustments.

It exposes only one method, that belongs to the window.performance object, called now(). It returns aDOMHighResTimeStamp representing the current time in milliseconds. The timestamp is very accurate, with precision to a thousandth of a millisecond, allowing for accurate tests of the performance of our code.

The most important feature of this method is that performance.now() is monotonically increasing (that is, it increases consistently), so the difference between two calls will never be negative.

A basic example of calling this method is shown below:

1
var time = performance.now();

3. Navigation Timing API

Page load time is one of the most important aspects of the user experience. Unfortunately, troubleshooting a slow page load is not easy because there are many contributing factors. To help with this, in addition to the APIs considered above, the W3C have proposed the Navigation Timing API.

This API offers detailed timing information throughout the page load process accessible through the timingproperty of the window.performance object. In detail, it provides measurements related to page redirects, DNS lookup, time spent building the DOM, TCP connection establishment, and several other metrics.

Network Information API

Another API that deals with performance is the Network Information API. It helps you discover whether the user is on a metered connection, such as pay-as-you-go, and provides an estimate of bandwidth. Thanks to this information, it’s possible to change the behaviour of our pages to accommodate a user in the best way possible. For example, we could conditionally load images, videos, fonts and other resources based on the type of connection detected.

This API belongs to the connection property of the window.navigator object. It exposes two read-only properties: bandwidth and metered. The former is a number representing an estimation of the current bandwidth, while the latter is a Boolean whose value is true if the user’s connection is subject to limitation and bandwidth usage, and false otherwise.

5. Vibration API

Another key concept that gets a lot of attention in our industry is user experience (UX). One of the APIs proposed that allows us to enhance this aspect of our websites is the Vibration API.

This API is designed to address use cases where touch-based feedback is required, and offers the ability to programmatically produce a vibration interacting with the mobile device’s built-in vibration hardware component. If such a component doesn’t exist, it does nothing.

The Vibration API is particularly useful if you’re working with online videos or web games. For example, you could let the user’s device vibrate during the progress of the game in reaction to a particular event.

It exposes only one method, vibrate(), that belongs to the window.navigator object. This method accepts one parameter specifying the duration of the vibration in milliseconds. The parameter can be either an integer or an array of integers. In the second case, it’s interpreted as alternating vibration times and pauses.

A basic use of this API is shown below:

1
2
// Vibrate once for 2 seconds
navigator.vibrate(2000);

6. Battery Status API

The Vibration API isn’t the only one that allows access to a device’s hardware. Another API of this type, designed with mobile devices in mind, is the Battery Status API. It allows you to inspect the state of a device’s battery and fires events about changes in battery level or status.

The Battery Status API exposes four properties (charging, chargingTime, discharingTime, andlevel) and four events. The properties specify if the battery is in charge, the seconds remaining until the battery is fully charged, the seconds remaining until the battery is fully discharged, and the current level of the battery. These properties belongs to the battery property of the window.navigator object.

7. Page Visibility API

The Page Visibility API enables us to determine the current visibility state of the page. What this means is that we’re able to detect if our page is in the background or minimized (i.e. it’s not the currently-focused window).

This capability can help us to develop powerful, yet CPU and bandwidth efficient web applications. In fact, we can slow down or even stop a CPU and/or bandwidth consuming process if we detect the user isn’t using the page.

This API exposes one event, called visibilitychange, that we can listen for to detect changes in the state of the page’s visibility, and two read-only properties, hidden and visibilityState. These properties belong to the document object. hidden is a Boolean whose value is true if the page is not visible, andfalse otherwise. visibilityState is an enumeration that specifies the current state of the document and consists of the following values: hidden, visible, prerender, and unloaded.

8. Fullscreen API

The Fullscreen API provides a way to request fullscreen display from the user, and exit this mode when desired.

This API exposes two methods, requestFullscreen() and exitFullscreen(), allowing us to request an element to become fullscreen and to exit fullscreen.

It also exposes two properties, fullScreenElement and fullScreenEnabled, belonging to the documentobject. These specify the element that has been pushed to fullscreen and if fullscreen mode is currently enabled. It also exposes one event, fullScreenEnabled, which provides us a convenient way to listen for when fullscreen mode has been enabled or disabled.

9. getUserMedia API

The getUserMedia API provides access to multimedia streams (video, audio, or both) from local devices. This means that we can access these streams without the use of Flash or Silverlight. Some use cases for this API include real-time communication and tutorials or lesson recording.

The getUserMedia API exposes just one method called getUserMedia(). It belongs to thewindow.navigator object and accepts as its parameters an object of constraints, a success callback, and a failure callback.

The getUserMedia API also allows us to have a lot of control over the requested stream. For example, we can choose to retrieve a video source at high resolution or at low resolution.

  • Offline apps – This API allows marking pages to be available in Offline mode. This is useful if a resource requires dynamic processing.
  • Indexed database – This API is meant for a database of records holding simple values (including hierarchical objects). Every record has a key and a value. An indexed database is supposed to be implemented using b-trees. Web SQL DB is no longer being pursued as part of HTML5 specification.
  • Web workers – This API is meant to be invoked by web application to spawn background workers to execute scripts which run in parallel to UI page. The concept of web works is similar to worker threads which get spawned for tasks which need to invoked separate from the UI thread.
  • Web storage – This specification defines an API for persistent data storage of key-value pair data in Web clients.
  • Web sockets – This API used for persisting data storage of data in a key-value pair format for Web clients.
    • Server-Sent Events – This API is used for opening an HTTP connection to receive push notifications from a server. These events are received as DOM events. This API is supposed to be used with Push SMS.
    • XMLHttpRequest2 – This API is used to provide scripted client functionality to transfer data between a server and a client.
    • Geolocation – This API is used to provide web applications with scripted access to geographical location information of the hosting device.
    • Canvas 2D Context – This API provides objects, methods and properties to draw and manipulate graphics on a canvas drawing surface.
    • HTML Microdata – This API is used to annotate content with specific machine-readable labels, e.g. to allow generic scripts to provide services that are customized to a page. Microdata allows nested groups of name-value pairs to be added to documents.
    • Media Capture – This API is used to facilitate user access to a device’s media capture mechanism (camera, microphone, file upload control, etc.). This only coves a subset of media capture functionality of the web platform.
    • Web Messaging – This API is used for communications between browsing contexts in HTML documents.
    • Forms – The Forms API can be used with the new data types supported with HTML5.
    • File API – The File APIs are used by the browser to provide secure access to the file system.

How many ways an object can be created in javascript

7 ways to create objects in Javascript

Javascript is one of the few object oriented languages without classes. Nevertheless it is possible to create new objects choosing among several different techniques some of which may seem confusing to the newbies.
In this article I will go through seven different ways to create objects in Javascript, pointing out the pros and cons in each of them.
Before starting, it is worth remembering that a Javascript object is a simple collection of properties. Each property is a key-value pair. The value can be a primitive type, an object, or a function. Properties can be added, updated or removed at any time.

1. Object constructor

The simplest way to create an object is to use the Object constructor:

view plainprint?

  1. varperson = new Object();
  2. person.name= “Diego”;
  3. person.getName = function(){
  4. return this.name;
  5. };

The main advantage of this approach is its simplicity.
On the other hand, instantiating multiple objects of the same type leads to a lot of code duplication. Moreover, it is not a compact construct which means it is not intuitively straightforward in pointing out to where the object’s construction ends.

2. Literal notation

view plainprint?

  1. varperson = {
  2. person.name : “Diego”,
  3. person.getName : function(){
  4. return this.name;
  5. }
  6. }

While the literal notation is more compact and elegant than the Object constructor, it is still not reusable.

3. Factory function

The Factory function allows to encapsulate and re-use the logic for creating similar objects. It leverages any of the previous constructs for this.
Either:

view plainprint?

  1. varnewPerson=function(name){
  2. var result = new Object();
  3. result.name = name;
  4. result.getName = function(){
  5. return this.name;
  6. };
  7. return result;
  8. };
  9. varpersonOne = newPerson(“Diego”);
  10. varpersonTwo = newPerson(“Gangelo”);
  11. console.log(personOne.getName()); // prints Diego
  12. console.log(personTwo.getName()); // prints Gangelo

Or:

view plainprint?

  1. varnewPerson=function(name){
  2. return {
  3. person.name : name,
  4. person.getName : function(){
  5. return this.name;
  6. };
  7. };
  8. varpersonOne = newPerson(“Diego”);
  9. varpersonTwo = newPerson(“Gangelo”);
  10. console.log(personOne.getName()); // prints Diego
  11. console.log(personTwo.getName()); // prints Gangelo

Code re-use and encapsulation are the main advantages of this pattern.
Now suppose you have an object X at a certain point in your code. How do you determine if X is a person or not? You could use some ad-hoc technique but the most elegant approach would be to interrogate theinstanceOf operator.

4. Function Constructor

In Javascript it is possible to call any function with the new operator in front of it.
Given a function F, for new F():

  • a new empty object X is created.
  • X is set as context for F meaning throughout Fthis points to X.
  • X is returned as result of F

view plainprint?

  1. functionPerson(name){
  2. this.name = name;
  3. this.getName = function(){
  4. return this.name;
  5. };
  6. };
  7. varpersonOne = new Person(“Diego”);
  8. console.log(personOne.getName()); // prints Diego
  9. console.log(personOne instanceOf Person); // prints true
  10. console.log(personOne.constructor === Person); // prints true
  11. console.log(personOne instanceOf Object); // prints true

This time instanceof behaves the way we desired.

The constructor pattern is compact, reusable and gives a classical OO syntax.
Still, it is not perfect! In our example the field getName is a function. In Javascript functions are objects. Same function defined ten times means ten different objects created. Escalate this to a thousand and realize how much memory is being wasted!
It would be nice if all instances of Person share the same getName object, since this holds behavior and not data.

5. Prototype

Functions are very special in Javascript. They are objects, they can create other objects and they automatically get a field called prototype.
A prototype is a plain object with a single field, called constructor, pointing to the function itself.
What makes it special is that every object created through a function inherits the function’s prototype.

view plainprint?

  1. functionPerson(){};
  2. Person.prototype.name= “Diego”;
  3. varpersonOne = new Person();
  4. varpersonTwo = new Person();
  5. console.log(personOne.constructor == Person); // prints true
  6. console.log(personOne.name); // prints Diego
  7. console.log(personTwo.constructor == Person); // prints true
  8. console.log(personTwo.name); // prints Diego

Let’s see more in detail what happens:

  • Line 1:Person function is created. It automatically gets the prototype field.
  • Line 2: A field calledname is added to Person’s prototype.
  • Lines 3 and 4: Two instances of Person are created. They both get a field called__proto__pointing to Person’s prototype.
  • The last four lines show how the two objects share all properties present in Person’s prototype

Why is the name field accessible directly from the object and not through the __proto__ field?
In order to answer this, we first have to understand how property lookup works in Javascript.
Suppose you want to access a field called name in an object foo:

  • iffoo has a property name, the relative value is returned.
  • iffoo does not have a property name but __proto__ does, __proto__’s value is returned.
  • if neitherfoo nor __proto__ have the property, then __proto__’s prototype is checked. And so on…

Due to time and space constraints, I will not talk more about prototypes except emphasizing that not all Javascript implementations provide access to __proto__. Therefore, it is better if you never try to access it.

The prototype pattern solves the issues encountered within the function constructor.
On the other hand, the opposite problem arises: All instances share the same fields. This is good for functions, but not for the rest!

view plainprint?

  1. personOne.name = “Filippo”;
  2. console.log(personOne.name); // prints Filippo
  3. console.log(personTwo.name); // prints Filippo

6. Function/Prototype combination

The function/prototype combination, as you would imagine, takes advantage of both approaches 🙂

view plainprint?

  1. functionPerson(name){
  2. this.name = name;
  3. };
  4. Person.prototype.getName = function(){
  5. return this.name;
  6. };
  7. varpersonOne = new Person(“Diego”);
  8. varpersonTwo = new Person(“Filippo”);
  9. console.log(personOne.getName()); // prints Diego
  10. console.log(personTwo.getName()); // prints Filippo
  11. console.log(personOne.getName === personTwo.getName) //prints true

While sharing behavior (the getName function), each object has its own data and state.

7. Singleton

Sometimes, you may want to make sure that only a single instance of a certain class exists.
To get a Singleton in Javascript is as simple as defining and invoking the constructor at the same time:

view plainprint?

  1. varsingleton = new function(){
  2. this.name = “ApplicationName”;
  3. };