Object-oriented programming

Object-oriented programming is a programming paradigm that uses abstraction to create models based on the real world. It uses several techniques from previously established paradigms, including modularity, polymorphism, and encapsulation. Today, many popular programming languages (such as Java, JavaScript, C#, C++, Python, PHP, Ruby and Objective-C) support object-oriented programming (OOP).

Object-oriented programming may be seen as the design of software using a collection of cooperating objects, as opposed to a traditional view in which a program may be seen as a collection of functions, or simply as a list of instructions to the computer. In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects. Each object can be viewed as an independent little machine with a distinct role or responsibility.

Object-oriented programming is intended to promote greater flexibility and maintainability in programming, and is widely popular in large-scale software engineering. By virtue of its strong emphasis on modularity, object oriented code is intended to be simpler to develop and easier to understand later on, lending itself to more direct analysis, coding, and understanding of complex situations and procedures than less modular programming methods.1

Prototype-based programming

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is accomplished through a process of decorating existing objects which serve as prototypes. This model is also known as class-less, prototype-oriented, or instance-based programming.

The original (and most canonical) example of a prototype-based language is the programming language Self developed by David Ungar and Randall Smith. However, the class-less programming style has recently grown increasingly popular, and has been adopted for programming languages such as JavaScript, Cecil, NewtonScript, Io, MOO, REBOL, Kevo, Squeak (when using the Viewer framework to manipulate Morphic components), and several others.1

JavaScript object oriented programming

Namespace

A namespace is a container which allows developers to bundle up all functionality under a unique, application-specific name. In JavaScript a namespace is just another object containing methods, properties and objects.

It is very important to note that there is no language-level difference between regular object and namespaces as there is in some other object-oriented languages.

The idea behind creating a namespace in JavaScript is simple: one global object is created and all variables, methods and functions become properties of that object. Use of namespaces also minimizes the possibility of name conflicts in an application.

Let's create a global object called MYAPP:

// global namespace
var MYAPP = MYAPP || {};

Here in above code sample we have first checked whether MYAPP is already defined (either in same file or in another file). If yes, then use the existing MYAPP global object, otherwise create an empty object called MYAPP which will encapsulate method, functions, variables and objects.

We can also create sub-namespaces:

// sub namespace
MYAPP.event = {};

Below is code syntax for creating namespace and adding variable, function and method:

Standard built-in objects

JavaScript has several objects included in its core, for example, there are objects like Math, Object, Array, and String. The example below shows how to use the Math object to get a random number by using its random() method.

console.log(Math.random());

Note: This and all further examples presume a function named console.log is defined globally. The console.log function is not actually a part of the JavaScript language itself.

Every object in JavaScript is an instance of the object Object and therefore inherits all its properties and methods.

Custom objects

The class

JavaScript is a prototype-based language which contains no class statement, such as is found in C++ or Java. This is sometimes confusing for programmers accustomed to languages with a class statement. Instead, JavaScript uses functions as classes. Defining a class is as easy as defining a function. In the example below we define a new class called Person.

var Person = function () {};

The object (class instance)

To create a new instance of an object obj we use the statement new obj, assigning the result (which is of type obj) to a variable to access it later.

In the example below we define a class named Person and we create two instances (person1 and person2).

var person1 = new Person();
var person2 = new Person();

Please also see Object.create for a new and alternative instantiation method.

The constructor

The constructor is called at the moment of instantiation (the moment when the object instance is created). The constructor is a method of the class. In JavaScript the function serves as the constructor of the object, therefore there is no need to explicitly define a constructor method. Every action declared in the class gets executed at the time of instantiation.

The constructor is used to set the object's properties or to call methods to prepare the object for use. Adding class methods and their definitions occurs using a different syntax described later in this article.

In the example below, the constructor of the class Person logs a message when a Person is instantiated.

The property (object attribute)

Properties are variables contained in the class; every instance of the object has those properties. Properties are set in the constructor (function) of the class so that they are created on each instance.

Working with properties from within the class is done using the keyword this, which refers to the current object. Accessing (reading or writing) a property outside of the class is done with the syntax: InstanceName.Property; this is the same syntax used by C++, Java, and a number of other languages. (Inside the class the syntax this.Property is used to get or set the property's value.)

In the example below we define the firstName property for the Person class and we define it at instantiation.

The methods

Methods follow the same logic as properties; the difference is that they are functions and they are defined as functions. Calling a method is similar to accessing a property, but you add () at the end of the method name, possibly with arguments. To define a method, assign a function to a named property of the class's prototype property; the name that the function is assigned to is the name that the method is called by on the object.

In the example below we define and use the method sayHello() for the Person class.

As that example shows, all of the references we have to the sayHello function — the one on person1, on Person.prototype, in the helloFunction variable, etc. — refer to the same function. The value of this during a call to the function depends on how we call it. In the common case when we call it in an expression where we got the function from an object property — person1.sayHello() — this is set to the object we got the function from (person1), which is why person1.sayHello() uses the name "Alice" and person2.sayHello() uses the name "Bob". But if we call it other ways, this is set differently: Calling it from a variable — helloFunction() — sets this to the global object (window, on browsers). Since that object (probably) doesn't have a firstName property, we end up with "Hello, I'm undefined". (That's in loose mode code; it would be different [an error] in strict mode, but to avoid confusion we won't go into detail here.) Or we can set this explicitly using Function#call (or Function#apply), as shown at the end of the example.

Inheritance

Inheritance is a way to create a class as a specialized version of one or more classes (JavaScript only supports single inheritance). The specialized class is commonly called the child, and the other class is commonly called the parent. In JavaScript you do this by assigning an instance of the parent class to the child class, and then specializing it. In modern browsers you can also use Object.create to implement inheritance.

JavaScript does not detect the child class prototype.constructor (see Object.prototype), so we must state that manually.

In the example below, we define the class Student as a child class of Person. Then we redefine the sayHello() method and add the sayGoodBye() method.

Regarding the Student.prototype = Object.create(Person.prototype); line: On older JavaScript engines without Object.create, one can either use a "polyfill" (aka "shim", see the linked article), or one can use a function that achieves the same result, such as:

See Object.create for more on what it does, and a shim for older engines.

Encapsulation

In the previous example, Student does not need to know how the Person class's walk() method is implemented, but still can use that method; the Student class doesn't need to explicitly define that method unless we want to change it. This is called encapsulation, by which every class packages data and methods into a single unit.

Information hiding is a common feature in other languages often as private and protected methods/properties. Even though you could simulate something like this on JavaScript, this is not a requirement to do Object Oriented programming.2

Abstraction

Abstraction is a mechanism that permits modeling the current part of the working problem. This can be achieved by inheritance (specialization), or composition. JavaScript achieves specialization by inheritance, and composition by letting instances of classes be the values of attributes of other objects.

The JavaScript Function class inherits from the Object class (this demonstrates specialization of the model) and the Function.prototype property is an instance of Object (this demonstrates composition).

Polymorphism

Just like all methods and properties are defined inside the prototype property, different classes can define methods with the same name; methods are scoped to the class in which they're defined. This is only true when the two classes do not hold a parent-child relation (when one does not inherit from the other in a chain of inheritance).

Notes

The techniques presented in this article to implement object-oriented programming are not the only ones that can be used in JavaScript, which is very flexible in terms of how object-oriented programming can be performed.

Similarly, the techniques shown here do not use any language hacks, nor do they mimic other languages' object theory implementations.

There are other techniques that make even more advanced object-oriented programming in JavaScript, but those are beyond the scope of this introductory article.