Subscribe via RSS Feed

Javascript in OOP Way – some interesting study

July 4, 2013 8 Comments

As we are moving towards a world of client side MVC, new frameworks of javascript are becoming extremely important.

We have posted here the Object Oriented Programming and other interesting facts  in Javascript with feature examples.

So below are the codes with Comments -

 
        // Some interesting facts about Javascript
	//
	// Javascript Object Definitions
	var newObject = new Object();
	var newObj = {};
	// Defining properties for an object
	newObject.blogname = "PhloxBlog";
	var blogname = newObject.blogname;

	console.log(blogname);

	newObj["blogtitle"] = "Technical Blogs";
	var blogtitle = newObj["blogtitle"];

	console.log(blogtitle);

	// Interesting nested object access in javascript
	var nestedaddress = {
		State: "West Bengal",
		address: {
			streetname: "4C, Chidam Mudi Lane",
			city : "Kolkata",
			pincode: "700006"
		}
	}
	console.log(nestedaddress.address.city);

	// Interesting facts about function in javascript
	// A function declaration -

	function averageout(x, y) {
		var avg = (x + y)/2;
		return avg;
	}

	console.log(averageout()); // print NaN
	console.log(averageout(2,3)); // average will be done for 2 values
	console.log(averageout(2,3,4)); // average will be done forfirst  2 values and last one will be ignored

	// now... functions have access to an additional variable inside - called arguments

	function averageoutonarguments() {
		var sum = 0;
		for (var i = 0, j = arguments.length; i < j; i++) { 			
                        sum += arguments[i]; 		
                }
 		return sum/arguments.length; 	
       }

 	console.log(averageoutonarguments(1, 2, 3, 4)); 	 	

        // Anonymous function in Javascript 	 	

        var simpleFunction = function() 	{ 	  
             var aStringvalue = 'My Value in Moon'; 	  
             function oneMoreString(val) { 			
                 return 'Altered Value is ' + ' ' +val; 		
             } 		
             console.log(oneMoreString(aStringvalue)); 	
        }

        simpleFunction(); 	 	

        // JavaScript is a prototype-based language which contains no class statement 	 	

        function makeAddressWith(streetno, streetaddress, city, state, country, pincode) { 		
            return { 			
                   streetno: streetno ,
  		   streetaddress: streetaddress,
                   city: city, 			
                   state: state, 			
                   country: country, 			
                   pincode: pincode 		
           } 	
       } 	 	

       function fullAddress(address) { 		
          return 'Full Address is -->>' + '\n' + address.streetno + ' ' + 
                  address.streetaddress + '\n' + address.city + ' ' + 
                  address.pincode + '\n' + address.state + ' ' + address.country;
	}

	function addressWithCityAndPincode(address) {
		return 'City and Pincode is -->>' + '\n' + address.city + ' ' + address.pincode ;
	}

	address = makeAddressWith("4C", "Chidam Mudi Lane", "Kolkata", "West Bengal", "India", "700006");

	console.log(fullAddress(address));
	console.log(addressWithCityAndPincode(address));

	// Now more concise definition of the class

	function makeAnotherAddressWith(streetno, streetaddress, city, state, country, pincode) {
		return {
			streetno: streetno ,
			streetaddress: streetaddress, 
			city: city,
			state: state,
			country: country,
			pincode: pincode,
			fullAddress: function() {
			          return 'Full Address is (another function) -->>' + '\n' + address.streetno + ' '                                          + address.streetaddress + '\n' + address.city + ' ' + address.pincode + 
                                         '\n' + address.state + ' ' + address.country;
			},
			addressWithCityAndPincode: function() {
				return 'City and Pincode is (another function) -->>' + '\n' + address.city + ' ' +                                 address.pincode ;
			}
		}
	}

	anotheraddress = makeAnotherAddressWith("4C", "Chidam Mudi Lane", "Kolkata", 
                                                    "West Bengal", "India", "700006");

	console.log(anotheraddress.fullAddress());
	console.log(anotheraddress.addressWithCityAndPincode());

	// Now it is use of prototype. SomeObject.prototype will be used by all instances of SomeObject. 
        // Also the use of 'this' and 'new' are done.

	function AddressWithPrototype(streetno, streetaddress, city, state, country, pincode) {
			this.streetno = streetno;
			this.streetaddress = streetaddress;
			this.city = city;
			this.state = state;
			this.country = country;
			this.pincode =  pincode;
		}

	AddressWithPrototype.prototype.fullAddress = function() {
		return 'Full Address is (prototype) -->>' + '\n' + this.streetno + ' ' + this.streetaddress + '\n'                         + this.city + ' ' + this.pincode + '\n' + this.state + ' ' + this.country;
	}

	AddressWithPrototype.prototype.addressWithCityAndPincode = function() {
		return 'City and Pincode is (prototype) -->>' + '\n' + this.city + ' ' + this.pincode ;
	}

	address1 = new AddressWithPrototype("4C", "Chidam Mudi Lane", "Kolkata", "West Bengal", "India", "700006");
	console.log(address1.fullAddress());
	address2 = new AddressWithPrototype("5C", "Chidam Mudi Lane", "Kolkata", "West Bengal", "India", "700034");
	console.log(address2.addressWithCityAndPincode());
	// Adding extra methods at prototype

	AddressWithPrototype.prototype.addressWithStateAndCountry = function() {
		return 'State and Country is (prototype) -->>' + '\n' + this.state + ' ' + this.country ;
	}

	address3 = new AddressWithPrototype("5C", "Chidam Mudi Lane", "Kolkata", "East Bengal", "India", "700034");
	console.log(address3.addressWithStateAndCountry());

	// Inner functions

	function anOuterFunction() {
		var a = 1;
		function innerFunction() {
			return a + 1;
		}
		return innerFunction();
	}
	console.log(anOuterFunction());

	// Javascript Closures (Cleverly confusing....)

	function closureFunction(a) {
		return function(b) {
			return a + b;
		}
	}
	x = closureFunction(5);
	y = closureFunction(20);

	console.log(x(6));
	console.log(y(7));

	// Class in Javascript

	function Blog() { }

	// The Object (Class Instances) in javascript

	function BlogAuthor() { }

	var firstPerson = new BlogAuthor();
	var secondPerson = new BlogAuthor();

	// The Constructor in jaascript

	function BlogContent() {
	  console.log('BlogContent instantiated');
	}

	var content1 = new BlogContent();
	var content2 = new BlogContent();

	// The property (object attribute) in javascript

	function BlogModerator(name) {
	  this.name = name;
	  console.log('BlogModerator instantiated');
	}

	var bm = new BlogModerator('My Name');

	// display the blog moderator name
	console.log('Blog moderator is  ' + bm.name); 

	// The methods

	function BlogComment(username) {
	  this.username = username;
	  console.log('Blog Comment instantiated');
	}

	BlogComment.prototype.comment = function()
	{
	  console.log('This is a nice one by '+ this.username);
	};

	var comment1 = new BlogComment('Bob');
	var comment2 = new BlogComment('Michael');

	// call the BlogComment comment method.

	comment1.comment(); 
	comment2.comment(); 

	// Inheritance in JavaScript

	// define the Post Class

	function Post() {}

	Post.prototype.createpost = function(){
	  console.log('A post is created in draft mode');
	};
	Post.prototype.save = function(){
	  console.log('Post is saved');
	};

	// define the Technical Post class
	function TechnicalPost() {
	  // Call the parent constructor
	  Post.call(this);
	}

	// inherit Post
	TechnicalPost.prototype = new Post();

	// correct the constructor pointer because previously it points to Post
	TechnicalPost.prototype.constructor = TechnicalPost;

	// replace the save method
	TechnicalPost.prototype.save = function(){
	  console.log('Post is now TechnicalPost');
	}

	// add publish method
	TechnicalPost.prototype.publish = function(){
	  console.log('TechnicalPost is published');
	}

	var post = new TechnicalPost();
	post.createpost();
	post.save();
	post.publish();

	// check inheritance
	console.log(post instanceof Post); // true 
	console.log(post instanceof TechnicalPost); // true

	// Using Object.create the inheritance line would instead be

	TechnicalPost.prototype = Object.create(Post.prototype);

	// Encapsulation

	// TechnicalPost does not need to know the body of Post class's createpost() method, 
	// but can use that method; the TechnicalPost class doesn't need to define the method unless we need 
        // to use it 
	// This is encapsulation, by which every class inherits the methods of its parent and only needs to define         // things it wishes to change. Also the child class can define other methods.

javascriptnosqlbook
Reference :

A re-introduction to JavaScript (JS Tutorial)

Introduction to Object-Oriented JavaScript

Also if you find this article helpful, you can connect us in Google+ and Twitter.

Enter your email address:

Delivered by FeedBurner

javascriptnosqlbook