Vinod Sebastian – B.Tech, M.Com, PGCBM, PGCPM, PGDBIO

Hi I'm a Web Architect by Profession and an Artist by nature. I love empowering People, aligning to Processes and delivering Projects.

Advertisements

Object Oriented Programming in JavaScript

Introduction

JavaScript is a class-free object-oriented language that utilizes prototypal inheritance instead of classical inheritance. This means that objects can directly inherit from other objects.

Basic Concepts

In JavaScript, objects are created using constructor functions. Below is an example of defining a class and creating an object:


function myClass() {
    this.prop = prop1; 
    this.method = method1; 
}

function method1() {
}

var myClassObj = new myClass();
myClassObj.prop = 2;

Key Points

  • Functions can simulate objects in JavaScript. The “this” keyword is used to specify that a member is part of the function object.
  • Prototype is used to extend properties and methods to all instances of a class, acting as a template.
  • Function definitions can lead to name clashes when defined outside a class, hence it’s recommended to define them inside the class.
  • Anonymous functions can be used to create function literals, leading to closures.
  • Methods can be created using the syntax function.method("methodname", function(){}).

Inheritance and Augmentation

  • To inherit from another function, you can use function1.inherits(function2).
  • To access a super method, the uber() method can be used, like this.uber("functionname").
  • Swiss inheritance allows for inheriting specific methods to prevent name collisions in multiple inheritance scenarios.
  • Class augmentation involves adding methods to a class, which will be available to all instances of that class. Object augmentation is adding a method to a specific object instance.

Parasitic Inheritance

In parasitic inheritance, a new object is created within the constructor or function of the parent class. This object is then modified and returned, leading to privileged methods. Below is an example:


function myClass(value) {
    var that = new baseClass(value);
    that.toString = function () {}; // Override the baseClass method
    return that;
}
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x