Skip navigation

Tag Archives: OOPs

this is powerful but at the same time if used without care it is dangerous too. Consider the example snippet below

// define Human class
var Human = function(name) { = name;
    this.say = function(){
        return "I am " +;
var author = new Human('raja');
var badAuthor = Human('ford');  // new keyword missing

alert(typeof author); // object
alert(typeof badAuthor); // undefined because context changed to window
alert(  // raja
alert(  // ford

Notice how missing new keyword changing the context to window object.

Play with it.

Interface is an important concept in object oriented programming. It helps to reuse the code effectively.
So what is interface?

Interface provides a way to define what methods an object should have but not how it should be implemented. Interface allows to group objects based on what features they provide.

Javascript does not come with built-in support for interface. So in JavaScript it has to be manually ensure that a given class implements an interface.

Three ways to ensure interface in JavaScript:

  • Comments,
  • Attribute checking,
  • Duck typing
interface BasicMember {
    function isMajor(age);
    function isCitizen(ssn);
interface GoldMember {
    function havingVisaCard(ccn);
var RentACar = function(user, vehicle) { // implements BasicMember, GoldMember
    // ...
// Implement the BasicMember interface
RentACar.prototype.isMajor = function(age) {
    // ...
RentACar.prototype.isCitizen = function(ssn) {
    // ...
// Implement the GoldMember interface
RentACar.prototype.havingVisaCard = function(ccn) {
    // ...

This is just kind of documentation, Compliance is voluntary. Other two types will be explained in forth coming posts.

To understand the  constructor, consider the following code

// constructor function definition
function sum(a,b){; = a + b;

// create object using sum constructor
var sal = new sum(3,3);

alert(;  // 6
alert(sal.constructor)  // displays function definition above

Now sal is object of type sum.

Interesting part is you can create sum object using sal though constructor property. Here is how…

var sal1 = new sal.constructor(5,5);
alert(;  // 10