CodeSamplez

Programming Tutorials And Source Code Examples

  • Facebook
  • Google+
  • RSS
  • Twitter
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact
Home Programming Object Oriented JavaScript: Inheritance, (Static) Method

Object Oriented JavaScript: Inheritance, (Static) Method

Rana Ahsan November 22, 2014 Leave a Comment


 Object Oriented JavaScript: Inheritance, (Static) Method    

This is a follow-up article of my earlier post on JavaScript class basics. There are some few more things that we actually need to dive into object-oriented programming in JavaScript. Today, In this tutorial, I will try to describe how we can leverage the power of inheritance in JavaScript program. We will also learn, how to declare a normal instance method and as well static method too.

Declaring A Method:

we can do it in two ways. one from inside the class as below:

function A()
{
    this.a = 10;
    this.funcA = function(){
        return this.a;
    }
}

or from outside the main scope, using the prototype keyword, as below:

B.prototype.funcA = function(){
        return this.a;
    }

Both of the declaration will work in the same way.

JavaScript Inheritance With ‘prototype’:

Besides, generic function/attribute declaration in outside of the original scope, this keyword is also taking care of the responsibilities of the OOP inheritance concept. this keyword is itself an object and all kind of JavaScript class also has this property, regardless we do or do not declare one.

Unlike some-kind of ‘extends’ type of keyword, we will need to use this. Lets see a small code example to get more clear idea about it:


function B()
{
    this.b = 20;
}
B.prototype = new A();


var objB = new B();
var objA = new A();
console.log(objB.funcA());
console.log(A.prototype);
console.log(B.prototype);

This will give us some output like as below:

10
{}
{ a: 10, funcA: [Function] }

Lets understand what is happening here. As I already said, the ‘prototype’ is itself is an object, we will have to assign an object to it by creating an instance of A class. As soon as we do it, the attributes/methods inside A will also be available inside B, which allows method call like ‘objB.funcA()’ accessible.

Even if we haven’t assigned anything to the ‘prototype’ property of class A, but still it is internally available as an empty object, thus giving the second output.

And sure, as we already assigned something to B class’s prototype, we will get the attributes/methods of A listed here as the third output.

Overriding Existing Method:

It’s very simple like defining a new method. So, lets say, we want to inherit the funcA with a little different implementation so that it returns the value of ‘b’ attribute instead of ‘a’. We can simply write something like follow to achieve that:

B.prototype.funcA = function() {
    return this.b;
}

Now it should give you output as value of ‘b’, not ‘a’, if you try with ‘objB.funcA()’ call. Also, same rule apply if you try to override some native existing method. JavaScript is so flexible, isn’t it??

Declaring Static Method:

Well, as you are using JavaScript classes, its natural that at some point you will feel the need of static methods as an object-oriented programmer, such as while trying to implement singleton pattern, adding a static constructor, helper function or factory method etc. Luckily we can achieve that too in JavaScript easily.

Again, there is no ‘static’ keyword here, but you can just assign the function directly instead of using the ‘prototype’ keyword, which causes creating instance method. Here is an example(assuming you have the previously shown code already):

B.fromData = function(data) {
    var b = new B();
    b.a = data.a;
    b.b = data.b;
    return b;
}

var objB2 = B.fromData({a:5,b:6});
console.log(objB2.funcA());

As you can see, we are now creating an instance of B from inside a static method declared inside itself. sure we will get an output of ‘6’ here, as expected.

Final Words:

Do you think something is missing here that would be nice to have for more clear understanding? Then, let me know via comments! Start enjoying this growing dynamic language in OOP style! Happy coding!

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

Filed Under: Programming Tagged With: javascript, oop

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.

Twitter: @ranacseruet
Github: ranacseruet

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • Generate HTTP Requests using c#
  • How To Work With JSON In Node.js / JavaScript
  • How To Work With C# Serial Port Communication
  • PHP HTML5 Video Streaming Tutorial
  • 8 Most Frequently Used And Useful PHP Array Operations
  • Get Facebook C# Api Access Token
  • How To Work With Multithreaded Programming In C#.NET Application
  • Tutorial On Uploading File With CodeIgniter Framework / PHP
  • Facebook C# API Tutorials
  • Control HTML5 Audio With Jquery
Follow Us On Twitter

Recent Tutorials

  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch
  • Getting Started With NVML Python API

Recent Comments

  • prem on PHP HTML5 Video Streaming Tutorial
  • Luis Villarroel on LinQ Query With Like Operator
  • Yanming Wei on PHP HTML5 Video Streaming Tutorial
  • Adolfo on Apple Push Notification Backend In NodeJS
  • NganKhuong on How To Work With JSON In Node.js / JavaScript

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2019 · CodeSamplez.com ·