Object Oriented JavaScript – Basics

All about JavaScript Objects

JavaScript has simple as well as complex data types.

Simple ones are 

1) Number

2) String

3) Boolean

4) Undefined and 

5) Null 

These are also referred to as immutable data types because they cannot be changed.

Apart from these primitive data types, JavaScript has a complex data type called Object.

The object data type is Mutable because it can be changed.

Objects are complex data types which are made up of other primitive data types such as number or Boolean or string. These data types are stored in the form of name and value pair.

For example,

var myShows = { suspense : “Lost”, drama: “One Tree Hill” }

In the above example of TV shows and genres, genre type is called “Property” and the name of the show as its “value”. In the above example, suspense is a property and Lost is a value.

Instead of String value if we assign a function to it then it will be called as Method instead of property.

If we modify above object to 

var myShows = { 

                                   suspense : “Lost”,

                                   drama: “One Tree Hill”, 

                                   is_watching: function(){ alert(“Yes !”); }

                              }

Here is_watching would be called Method instead of property because its value is a function.

Now that we are done with the basic concept of objects, let’s see how we use objects in real life and operations that can be performed on them.

1) How to create JavaScript objects and use inheritance 

2) How to access properties and methods of JavaScript objects

3) How JavaScript objects are stored

4) Property attributes of JavaScript objects

5) How to list properties of JavaScript objects

6) How to delete properties of objects 

7) How to send and receive data over HTTP using JavaScript object

How to create JavaScript objects and the use of inheritance 

Before that, a quick thing to remember, every function in JavaScript is also an object.

We can create objects in two ways

1) Using object literal notation 

2) Using Constructor (and a new keyword)

Using object literal

We can simply create an empty object by assigning a variable to a pair of curly braces like below.

var myObj = {};

That’s it you got your brand new object just like that.

Using constructor and a new operator

var myObj = new Object();

Later you can add whatever properties and methods (functions) to it as you please.

For example,

    myObj.name = “Deepak”

    myObj.fetchName = function (){ console.log(this.name)};

                  

Which one is the better approach then?

Well, it depends on the usage, I like the modified one, yeap there is another one.

Functions are also objects, remember? So third way is kind of derived from the second one but with parameters and there is a use of ‘this’ keyword.

Let’s take an example,

function FavShow(showName, showTime, showRating){

                    this.getShowDetails = function(){

                                   console.log(” Name-” + showName);

                                   console.log(” Time-” + showTime);

                                   console.log(” Rating-” + showRating);

                 };

}

var lostShow = new FavShow(“LOST”, “9:00PM”, “8.9”);

lostShow.getShowDetails(); // Name-LOST Time-9:00PM Rating-8.9

here is a jsbin demonstration.

http://jsbin.com/ligahe/6/edit?js,console

Okay, so let’s take it a little further what did we just do?

We created an object that takes arguments, this is called the constructor pattern.

So, lostShow has been constructed using FavShow.

lostShow has no properties of its own but it has inherited properties of FavShow.

If we wish to add another method to lostShow object we can do following,

lostShow.myOwnMethod = function () {

console.log(“Happy Feet”);

   }

So now lostShow object has its method “myOwnMethod” and one inherited method from FavShow which is getShowDetails.

But, since we used this keyword in FavShow, the lost show will have its instance of the getShowDetails function. 

Object’s Own and Inherited Properties

As we discussed earlier objects can inherit properties and methods from parent objects when created using the new operator.

Also, we can define properties and methods on the new objects themselves.

For instance,

Function parentShow(){

   this.name = “originals”;

}

var derivedShow = new parentShow();

derivedShow.genre = “mythology”;

//Now genre property is defined on derivedShow which is not inherited. These kinds of properties and methods are called own properties and methods.

There are a few functions available to check whether a given property is owned by an object or inherited.

hasOwnProperty is one of such functions that returns true or false.

If we want to use it in above example,

console.log(derivedShow.hasOwnPropery(“name”)); //outputs False

console.log(derivedShow.hasOwnPropery(“genre”)); //outputs True

 To find out if a property exists at all on an object (either as an inherited or an own property), you use the in operator

console.log(“genre in parentShow”); //outputs false

console.log(“genre in derivedShow”); //outputs true

console.log(“name in derivedShow”); //outputs true since this property is inherited from parentShow

To create a method or a property which will be shared among all the objects derived from the parent we need to define it on an inbuilt property of an object called prototype.

Here is my JSBIN link to play around 

http://jsbin.com/tafeja/3/edit?js,console

//Let’s create a simple object. 

//function is also objects and is used to create parameterized constructors.

function myTVShow() {

 this.name = “Ray Donavan”;

 this.getTime = function() {

   console.log(“Friday 8:30PM”);

 }

};

// we simply defined a function object having one property and new method.

//Let’s create another object using constructor pattern

var newShow = new myTVShow();

//Now newShow will have instances of a name and getTime methods as inherited property and method respectively. 

//To access this property (name) and a method (getTime) we can use a dot operator.

newShow.getTime();

In the above example, every new object will have its instance of properties and methods 

But what if we want to create an object or a method to share between all the objects?

To create a method or a property which will be shared among all the objects derived from the parent we need to define it on an inbuilt property of an object called prototype.

//and thus you will be able to add new properties even run time and also make them available to all other inherited objects. 

myTVShow.prototype.setTime = function (){console.log(“New Time Set – Sunday 7:30 PM !”)};

newShow.setTime(); //and it will be shared among all other objects as well

//Let’s try one more thing, what if we defined property or method on base parent object directly and not on the prototype, will that still be available to child objects?

// uncomment following lines to run 

/*myTVShow.tryThis = function(){

   console.log(“Marvel is awesome, but will it work ?”);

}

newShow.tryThis();*/

//We get an error tryThis is not a function

//Now if we change this to prototype again, it’ll work

myTVShow.prototype.tryThis = function(){

   console.log(“Marvel is awesome, and it works !”);

}

newShow.tryThis(); // Outputs Marvel is awesome, and it works ! 

How to access properties and methods of JavaScript objects

To access properties and methods of an object we can use both dot operator and also bracket notation just like an array.

Remember arrays are also a special type of objects where properties (indices) are numbers and accessed using square brackets.

Don’t be confused, we will see that later.

For Example,

Var Genre = {basic:”Drama”, fav:”Thriller”, popular:”Suspense”}

//To access a basic property of Genre object we can do this 

console.log(Genre.basic); //will output Drama

Alternatively, we can use this notation as well

console.log(Genre[“basic”]);

Remember we do not have associative arrays in js however we can use objects for the same purpose. 

The way to access values does resemble the way we access the associative array.

Here is just a basic comparison

  

  Object

  Array

  

  Declare

  Var myObj = {};

  Var myArray = [];

  

  

  Var myObj = new Object();

  Var myArray = new Array();

  

  Access

  myObj.propertyName;

or

myObj[“propertyName”]

  myArray[1];  

// can only use numeric indices and square brackets for arrays

  

 

Rules to define objects and access methods

1) The property name can be either number or String

2) If the property name is a string then use the dot operator to access it.

3) If the property name is a number then use bracket notation to access it.

Remember arrays are also a special type of object in JavaScript.

var showTime = {1:”8PM”, repeat:”9PM”}

To access repeat value we can use dot operator like var repeatTime = showTime.repeat however to access the value of 1 we need to do this,

var firstShow = showTime[1];

Call by value and illusion of call by reference

JavaScript only has called by value feature but in the case of objects, it feels like JavaScript also has called by reference. However, that is not true. In the case of objects, js pass a copy of reference (not even the original reference) to the function.

Call by value with primitive data types

The most important distinguishing features of call-by-value is:

If the function can assign values to its parameters, only its local copy is assigned — 

That is, anything passed into a function call is unchanged in the caller’s scope when the function returns.

function copyShow(show){

   console.log(show); // Will output Originals

}

var favShow = “Originals”;      

copyShow(favShow);      

                  

                  

Compare that to the definition of call-by-reference:

Call by reference typically means that the function can modify (i.e. assign to) 

the variable used as an argument — something that will be seen by its caller.

In other words, JavaScript treats references to objects just like values and those values are copied just like any other value when a function is called with an object for an argument.

Function copyFunction(oldShow){

oldShow.name = “Voice”;

}   

 var newShow = { name:”New Girl” };

                 

copyFunction(newShow);

Now if you print both the values you get the same output

console.log(oldShow.name); // outputs Voice

console.log(newShow.name); // outputs Voice

                 

Objects references are passed by value means even if you copy the old value in a variable, what you stored in a reference (Memory Location) to that variable and when you retrieve it, it will always fetch the latest value at that memory location.

Property attributes of JavaScript objects

Do you remember the definition of Metadata, yeah that’s right? It’s the data about the data.

In other words, they are attributes of data. In our case objects are data also properties inside the objects are.

So “Property” (name in name-value pair) also has attributes that define whether you can change the property or delete the property or can it be returned in a for or other loops.

These attributes are,

1) Configurable Attribute – Specifies whether the property can be deleted or changed.

2) Enumerable – Specifies whether the property can be returned in a for/in loop.

3) Writable – Specifies whether the property can be changed.

How to list properties of JavaScript objects

Consider a scenario where you wish to print out all the properties of an object but the trouble is you do not know the definition of that object.

We still can loop over the properties and print their names.

Properties that can be accessed in a loop like for loop are called enumerable properties.

Both inherited and own properties are enumerable. Except for prototype property.

parentShow = {

   name :”originals”,

   date : “Dec 2015”

}

for(var item in parentShow){

   console.log(item); // Prints name and date

}

To get values of these properties we can do the following 

for(var item in parentShow){

   console.log(parentShow[item]); // Prints name and date

}

Inherited properties can also be accessed the same way.

function parentShow(){

   this.name = “originals”;

   this.date = “Dec 2015”;

}

var newShow = new parentShow();

newShow.show = “Lost”;

for(var item in newShow){

   console.log(item);

}

// this will output name, date as inherited properties as well as the show as its property.

How to delete properties of objects 

// Demonstrate Deletion operations on object

// Define an object

// Remember the constructor way of defining function as an object

function Movies() {

   movie_name = “Avangers”;

   this.duration = “3 Hrs”;

}

// We are using ‘this’ keyword for the duration that will bind duration property to each instance of a new object which is created from Movies object. 

//However for movie_name we have not used ‘this’ and hence it will only be bound to Movies and will be accessible via prototype to other child objects. To check it quicky create a new object and run hasOwnProperty for both name and duration, the duration will return true and name will not. 

// Define sciFi object and inherit properties from movies object

var sciFi = new Movies();

console.log(“has own property ‘name’ ? = ” + sciFi.hasOwnProperty(“movie_name”)); //returns false

console.log(“has own property ‘duration’ ? = ” + sciFi.hasOwnProperty(“duration”)); //returns true

// Define a new property ‘Rating’ on sciFi object

// Now sciFi has three properties name and duration are inherited ones and rating as own propery

sciFi.rating = “* * * *”;

//1) We use delete operator to delete properties,

// Delete operator returns true whether it can delete or not. 

//2) We can delete the properties owned by the object itself but can not delete inherited properties from the object.

var success = delete sciFi.rating;

console.log(“Own Property ‘Rating’ Deleted = ” + success); //returns true since it’s own property

//let’s check whether rating property is actually deleted.

console.log(“*** Property checks after deletin Rating *** “);

for (var item in sciFi) {

   console.log(item); 

 // returns ‘duration’ which is inherited property and rating is deleted

}

// let’s try to delete name propertie

var success = delete sciFi.movie_name;

console.log(“Inherited Property name Deleted = ” + success);

//returns true even if it is not able to delete property ‘name’ of movies

// To delete inherited properties we need to define them on prototype object first

Movies.prototype.favMovie=”My Favourite Movie”;

console.log(“Check if you can access new property = ” +Movies.prototype.favMovie);

//now try and delete that property

var success = delete Movies.prototype.favMovie;

console.log(” Deleting on Prototype a new property favMovie – “+success); //returns true 

//let’s check whether name property is actually deleted.

console.log(“Check if inherited property is deleted using prototype”);

console.log(Movies.prototype.favMovie); // returns “My Favourite Movie”.

//3) since delete operator returns true in either case, we need to check whether it is owned by 

// object using hasOwnProperty.

Sending object via HTTP (Stringify and Parsing)

To send an object over Http we need to convert it into a string and after receiving the data we need to convert that string into the object again.

Converting the object into a string is called stringifying and the reverse process is called parsing.

To convert an object into a string we have a function called stringify and to convert a string into the object we have a function called parsing.

For example,

var channels = {name:”AXN”,popularity:”9 star”} ; 

var str = JSON.stringify(channels);

console.log(str); // outputs “{\”name\”:\”AXN\”,\”popularity\”:\”9 star\”}”

// if you want to format also with the converted string then all you need to do is pass some parameter to JSON.stringify function, null and 4 as follows

var str = JSON.stringify(channels,null,4);

console.log(str); 

outputs 

“{\”name\”: “AXN\”,

   \”popularity\”: \”9 star\”

}”

// To convert back stringified object into object use JSON. parse method

var obj = JSON.parse(str);

console.log(obj);

Outputs

[object Object] {

 name: “AXN”,

 popularity: “9 star”

}

You can access any property of this object as usual now.

console.log(obj.name); // will output AXN

Leave a Reply