Object Oriented Programming In Javascript Part One

For most developers JavaScript is like a procedural language. It's just a language that can interact with the DOM, Create Element in the HTML document, Listen to events and so on. But there is more than that we can do in JavaScript. You can actually implement Object Oriented programming in JavaScript. In-fact everything in Javascript is an Object as you will see later in this post.

This is not an introduction to Javascript, you must have some basic understanding of how Javascript works and some basics of it. You must also have some basic understanding of OOP.

Object

Except the simple types Numbers, String, Booleans, Null and undefined all the other values are objects in Javascript. Numbers, Strings and Booleans are Objects like. They have methods you can operate on, but the values are immutable (they cannot be changed). In Javascript Array, function and Regular Expressions are objects, also objects are objects.

Example
// The concat method will combine two string and returns the resulting string.
'Java'.concat('Script'); // output: JavaScript
// This will find the position of the substring in the given string.
'sub-string'.indexOf('-') // will return 3. Index starts form 0 to n-1 where n is the length of the string
    

In Javascript an object is a dynamic collection of properties. Every property of an object is a Key - Value Pair. The value pointed by the key can be any valid Javascript value, it can even be a function.

var testObject = {
  'property': 'String Property',
  'functionProperty': function () {
    return this.property;
  }
}

Objects in Javascript does not have a classname. They all are linked with a prototypical inheritance which we will later see in this series. You can add any number of properties to an object.

All the keys in an object must be a String. If it is not it will be converted to a string. If there are two key's with the same key-name the second one will replace the first one.

Example
// Object with a numeric key
var numericKeyObj = {
  234: 'This is a value of numeric key which will be converted to a string'
}

console.log(numericKeyObj['234']); // will log the value in the console.
console.log(numericKeyObj[234]); // will also return the string value.

You can access the object property in two styles. The Array Notation and the "." Dot Notation. You can see that we have used both in the above examples.

You can create object in Javascript using the Literal Notation or using the Object.create() method of the global Object. With Object.create you must specify the prototype of the new Object being created, it can either be an >Object or Null. But it must be specified.

// Creating a new object with the object literal notation.
var person = {
 firstName: 'John',
 age: 20,
 location: 'New York',
 getDetails: function() {
  return this.firstName + ' ' + this.age + ' ' + this.location;
 }
};

person.getDetails(); // will return "John 343 New York";
or
person['getDetails'](); // This will also work.

Objects are passed by Reference

Objects in Javascript are passed by reference. Any where the object value is changed it affects the original Object.

var John = {
 firstName: "John",
 age: 23,
 location: "New York",
 getDetails: function() {
  
 }
};

function changeFirstName(person) {
 person.firstName = "Scott";
}

changeFirstName(John);
// Now the firstName property of John is changed to “Scoot”
console.log(John.firstName);

Details of Property is not Yet Over

There are actually two type of properties. Data properties and Accessor properties. Data properties are just to store data like String and Integer values. Accessor properties are methods that work with the data in the object.

Every property is a named collection of attributes. Those attributes are as follows.

Note: These properties were always there in Javascript, but they were never exposed to the programmer. In ES5 this can be done.

Name Type Desc Example
value Any valid Javascript Value The Value of the property person.firstName has the string value "John"
writable boolean Weather this is readonly or writable. // you can do the following only if this bit is set to true. person.firstName = "Scott";
enumerable boolean Will this property appear in the for in iteration // the properties appear in the for in loop only when this is set. for (prop in person) console.log(prop);
configurable boolean Can we change or delete this property
get function Getter method for getting this value. function() {...}
set function Setter method.
Attributes bit of Javascript Object Properties

For you to define an object with setting this bits you can use the following methods.

Object.defineProperty(object, key, descriptor)
Object.defineProperties(object, object_of_descriptors)

With defineProperty you can create a single Object property by passing the object to create the property for, the name of the property as key and the bits as an Object which is the third argument.

defineProperties can be used to define multiple properties at once for an Object.

var person = Object.defineProperties(Object.create(Object.prototype), {
    firstName: {value: "John", writable: true, enumerable: true, configurable: true},
    age: {value: 20, writable: true, enumerable: true, configurable: true},
    location: {value: "New York", writable: true, enumerable: true, configurable: true},
    getDetails: {value: function() { return this.firstName + ' ' + this.age + ' ' + this.location; }, writable: true, enumerable: true, configurable: true},
});

This code does the same thing as the code shown initially to create the person object. It seems pretty complex, but it lets you modify the bits of the properties of the Object.

The following is the code where the object is created by modifying the bit.

var strictPerson = Object.defineProperties(Object.create(Object.prototype), {
    firstName: {value: "John", writable: false, enumerable: true, configurable: false},
    age: {value: 20, writable: false, enumerable: true, configurable: true},
    location: {value: "New York", writable: true, enumerable: true, configurable: false},
    getDetails: {value: function() { return this.firstName + ' ' + this.age + ' ' + this.location; }, writable: true, enumerable: false, configurable: false},
});

In the strictPerson object you cannot modify the value of firstName and age. You cannot delete the firstName, location and getDetails. The getDetails() method won't appear in the for in loop.

per.firstName = "Scott";
// will return "Scott", but the original value would not have been changed.
per.firstName
// The value has not been changed, it is still john "John"
delete per.firstName
// will return false, since its configurable bit is set to false.
delete per.age
// will return true.

for (prop in strictPerson) console.log(strictPerson[prop])
// will list all the property value except the getDetails method. since enumerable bit is set to off.

Creating Object in JavaScript

In Javascript object can be created either using the Literal Notation or Object.create() method as i told you before.

// literal notation
var newObj = {
 propertyOne: 'I am Property one'
};

// using Object.create()
var newObj = Object.create(Object.prototype);

New in ES5: Object now can be created with the prototype of the object set to null. By default the Object.prototype is set to the new Objects prototype. I will discus in detail about prototype in the next series.

Delegation

Delegation is when object "A" is passed as a reference to object "B" when "A" is knows something that object "B" doesn’t know. This is achieved through prototype in Javascript. Javascript is a prototype language. prototype is a concept that need a separate post of its own. If there is anything Scott does not knows, John may know it.

Reflection

Reflection is a method for inspecting the object properties. This can be done using the typeof keyword.

typeof per.firstName; // will return string
typeof per.age; // will return number
typeof per.getDetails; // will return function.

You can check if a Object has a property of its own by using the hasOwnProperty method.

per.hasOwnProperty(‘firstName’); // true
per.hasOwnProperty(‘lastName;); // false

Deleting a Object Property

You can delete a particular property of an object using the delete" keyword.

delete per.firstName; // will delete the firstName property

Note: If you need to know the methods available in an object, open the Google Chrome console or Mozilla Firefox console and type in the objectName and the list of available methods will appear.