JavaScript: functional or object oriented?

12:09 PM Xun 1 Comments

Question: Is the JavaScript languge functional or object oriented?
Answer: Both. And more.

Question: Should we use JavaScript primarily as a functional language or object orientated?
Answer: Depends (on your skill, taste, project needs).

Question: Are there examplary libraries that can be said as primarily functional or object orientated?
Answer: Well, most of the libraries are like JavaScript itself in that they support multiple programming paradigms. However, JQuery has a strong flavor of functional programming, while Ext.js is a completely object oriented javascript library.

Why? How?


First of All, object-oriented vs. functional

In OO programming, nearly everything is considered an object that has its set of state and behaviors. For example, a person have name and gender, a person talks and thinks. Classes are used to define the objects, states and behaviors are translated in members and methods. OO is considered as using classses and objects to mirror the real world of inter-connected hierachical entities, and break down complex system into smaller more manageable elements.


In functional programming, instead of objects, functions are the beginning and the end and everything in between. Functions are the building blocks of the programming. Individual functions are defined to perform individual tasks, such as compute, sort, translate; functions can be passed as arguments and results; functions can call themselves (recursion).

Objected oriented programming is the fashion of the current day programming, many languages are object-oriented languages,such as C#, Java; however, computer programs started out in functional programming, and lately functional programming languages are also staging a comeback, i.e., F#.

Objected-oriented and functional do not necessarily exclude each other.The Language Integrated Query (LINQ) feature, with its many incarnations, is powerful use of functional programming in .NET.; Java is sometimes said "impure" in Objected-oriented styles; While F# can use .NET types and objects and object-oriented style of programming.


JavaScript, functional?

Well, you may have recognize the characteritics of object-orientation and functional programming in such typical descriptions of JavaScript:

In JavaScript functions are first-class objects;

"JavaScript is fundamentally about objects. Arrays are objects. Functions are objects. Objects are objects. So what are objects? Objects are collections of name-value pairs. The names are strings, and the values are strings, numbers, booleans, and objects (including arrays and functions). Objects are usually implemented as hashtables so values can be retrieved quickly."

Private Members in JavaScript


Functions as first class objects


A lot about JavaScript functions fits in the bill of functional programming, the most obvious of which is anonymous functions that are widely used in event handlers and ajax calls.


$('#target').click(function() {
alert('Handler for .click() called.');
});


The flavor of functional programming in JQuery

The scent of functional programming in JQuery is particularly strong. There are three things make it so:
1) the JQuery variable, the magical dollar sign ($); 2) css selectors; 3) functional chain.

In JQuery, code like this is everywhere:

$("div.test").add("p.quote").html("a little test").fadeOut();


Dive into it, we can make three notes:

1) $, the biggest and all-encompassing jQuery object, started the chain. $ essentially is the wrapper of DOM object.
2)$ fetched the set of elements that are selected by the css selector using the expressing "div.test", meaning all divs with the class name test.
3) Chain operations a) add a little paragraph with class name quote; b) add a little html text c) have the div fade out.


The above three things typical of JQuery makes JQuery a perfect candidate in the family of functional programming; more precisely or nerdily, a monad.

The following is a definition of monad struction in Wiki:

"A monad is a programming structure that represents computations. Monads are a kind of abstract data type constructor that encapsulate program logic instead of data in the domain model."

/Monad_(functional_programming)


JavaScript, object oriented?

On the other hand, JavaScript is also perfectly object oriented. Almost everything in JavaScript is an object. And objects in JavaScript are extremely dynamic and meallable.

In JavaScript you can create an object in a few ways, the easiest is simply using call:


var x = new object();
x.name ="x";
x.tellName = function (){
alert(this.name)
};

Or you can use literal notation:


var x = {
name : "x",
tellName : function(){
alert("my name is " + this.name)
}
};


You can also accomplish inheritance in JavaScript in a few differnt fashions. For example, prototypal inheritance


function Person(name){
this.name=name;
}

Person.prototype.sayName=function(){
alert ( this.name);
}


Girl.prototype = new Person; // Here's where the inheritance occurs

function Girl(name){
// Let the Person function initialize the name by calling parent class' constructor
Person.call(this, name);
}

Girl.prototype.sayName=function(){
Person.prototype.sayName.call(this);
alert( "hi, I am a girl. my name is " +this.name );
}


var peter = new Person('peter');
peter.sayName();
var mary = new Girl('mary');
mary.sayName();


So in the above, we created a base class called Person, immediately we create a child class
called Girl. The inheritance takes place by set the prototype of Girl as new Person. We also
have the Girl inherit the Person's contructor by using

Person.prototype.sayName.call(this);


Lastly we overwrite the base class' sayName method by define its own.
function Girl(name){ 
// Let the Person function initialize the name by calling parent class' constructor
Person.call(this, name);
}




Ext.JS as an object-oriented JavaScript library

The Ext framework is completely fashioned around the object-oriented programming model. At the top of Ext library is the Ext namespace that encapsulates all classes, signletons and utiliy methods.

In new ext.js 4.0 library, the class system is as the following:




Take a look at Ext.Panel, which has the following hierarchy:


Let's look at some code of inheritance in Ext.js.

Ext.ns('MyApp');
/**
* @filename sillyPanel.js
* @class MyApp.sillyPanel
* @extends Ext.Panel
*/
MyApp.sillyPanel = Ext.extend(Ext.Panel, {

initComponent: function () {
var config = {
title: 'A silly Panel',
width: 120,
items: [{ html: "Nothing serious. A silly thing"}]
};

//Reusable config options here
Ext.apply(this, config);

// And Call the superclass to preserve baseclass functionality
MyApp.sillyPanel.superclass.initComponent.apply(this, arguments);
},
addSomethingExtra: function () {
}

});

A few observations from the above code sample of Ext inheritance

1) Namespace declaration. Ext.ns('MyApp'); Ext.ns is a shorthand for Ext.namespace. With a call of Ext.ns, it will create an object with the name supplied, if it does not already exist.

2) Ext extend is the utility function that implements class inheritance in the Ext framework.


3) Inside the extend, you provide the base class from which you are inheriting, and the extension details as the second argument. For more details on create Ext.js extensions, please view the Ext.js api.

To display the above coded silly panel on a page, you simply create a new silly panel on the Ext.onReady event.








My app tset page













Well, this concludes my rambling on the functional and object-oriented side of JavaScript,and my dabbling in features of JQuery and Ext.JS. In short, JavaScript is really a hodge podge of things, it really is flexible and mess. It supports a varity of programming styles, a lot of times you can get along not worrying about which camp you are in, but eventually as projects grows and your knowledge grows, you may need to think deeper and get to the root of why and how everything
happens in the way it does.

Source:
Functional vs. Object-Oriented JavaScript Development
JQuery: the very very basics

1 comment:

  1. Programming is very interesting and creative thing if you do it with love. Your blog code helps a lot to beginners to learn programming from basic to advance level. I really love this blog because I learn a lot from here and this process is still continuing.
    Love from Pro Programmer

    ReplyDelete