Thursday 23 April 2015

Object Oriented JavaScript

Javascript is prototype based language, no doubt JavaScript supports OOP concepts but not the way other languages support, other languages like Python, Java, C# has concept OOP by means of Class, before we go to deep how Javascript supports OOP concepts lets check what are the difference between object oriented based programming and prototype based programming and what are the basic features of Object oriented language.

Object-oriented programming

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

OOP envisions software as a collection of cooperating objects rather than a collection of functions or simply a list of commands (as is the traditional view). In OOP, each object can receive messages, process data, and send messages to other objects. Each object can be viewed as an independent little machine with a distinct role or responsibility.

OOP promotes greater flexibility and maintainability in programming, and is widely popular in large-scale software engineering. Because OOP strongly emphasizes modularity, object-oriented code is simpler to develop and easier to understand later on. Object-oriented code promotes more direct analysis, coding, and understanding of complex situations and procedures than less modular programming methods.

Concepts of OOP

Namespace
A container which lets developers bundle all functionality under a unique, application-specific name.
Class
Defines the object's characteristics. A class is a template definition of an object's properties and methods.
Object
An instance of a class.
Property
An object characteristic, such as color.
Method
An object capability, such as walk. It is a subroutine or function associated with a class.
Constructor
A method called at the moment an object is instantiated. It usually has the same name as the class containing it.
Inheritance
A class can inherit characteristics from another class.
Encapsulation
A method of bundling the data and methods that use the data.
Abstraction
The conjunction of an object's complex inheritance, methods, and properties must adequately reflect a reality model.
Polymorphism
Poly means "many" and morphism means "forms". Different classes might define the same method or property.

 

Prototype-based programming

Prototype-based programming is an OOP model that doesn't use classes, but rather accomplishes behavior reuse (equivalent to inheritance in class-based languages) by decorating (or expanding upon) existing prototype objects. (Also called classless, prototype-oriented, or instance-based programming.)

The original (and most canonical) example of a prototype-based language is Self developed by David Ungar and Randall Smith. However, the class-less programming style grows increasingly popular lately, 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.
Let's have a look each one of this and how JavaScript support each one of this.


JavaScript object oriented programming

Namespace

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

var odoo = window.odoo = {};


The idea behind creating a namespace in JavaScript is simple: create one global object, and all variables, methods, and functions become properties of that object. Use of namespaces also reduces the chance of name conflicts in an application, since each application's objects are properties of an application-defined global object.

We can also create sub-namespaces:

odoo.session = {}


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());
 

Custom objects

The class

JavaScript is a prototype-based language and 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 Session = 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 above we define a class named Session. In the example below we create two instances (session1 and session2).

var session1 = new Session();
var session2 = new Session();
 

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 Session logs a message when a Session is instantiated.
function Session(origin, use_cors) { 
    //Assigning values through constructor 
    this.init = function (origin, use_cors) {
        this.origin = origin;   
        this.use_cors = use_cors;
 
    //functions 
    this.authenticate = function(user, password) { 
        return user +" Has authentication on " + this.origin; 
    } 
    this.init(origin, use_cors); 
} 
//Creating session instance 
var session = new Session("http://localhost:8069", true); 
alert(session.authenticate('admin', 'password')); 

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.

The keyword this, which refers to the current object, lets you work with properties from within the class. Accessing (reading or writing) a property outside of the class is done with the syntax: InstanceName.Property, just like in C++, Java, and several 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 userName property for the Session class at instantiation:
var Session = function (userName) {
    this.userName = userName;
    console.log('Session instantiated');  
 };

var session = new Sesion('Alice');

// Show the firstName properties of the objects
console.log('session's username is ' + session.userName); // logs "session's username is Alice"

The methods

Methods are functions (and defined like functions), but otherwise follow the same logic as properties. 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. Later, you can call the method on the object by the same name as you assigned the function to.

In the example below, we define and use the method welcomeMessage() for the Session class.

var Session = function (userName, firstName) { 
    this.userName = userName; 
    this.firstName = firstName;
};

Session.prototype.welcomeMessage = function() {
  console.log("Hello, This is" + this.firstName + ", Welcoming you to learn Javascript");
};

var session = new Session('mohammed', "Mohammed Shekha");

// call the Session welcomeMessage method.
session.welcomeMessage(); // logs "Hello, This is Mohammed Shekha, Welcoming you to learn Javascript"


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.

Note: JavaScript does not detect the child class prototype.constructor (see Object.prototype), so we must state that manually. See the question "Why is it necessary to set the prototype constructor?" on Stackoverflow.

In the example below, we define the class CharWidget as a child class of Widget. Then we redefine the render() method and add the get_value() method.

// Define the Widget constructor
var Widget = function(node, name) { 
    this.name = name; 
    this.node = node;
};

// Add a couple of methods to Widget.prototype
Widget.prototype.walk = function(){
  console.log("I am walking!");
};

Widget.prototype.render = function(){
    console.log("Hello, I'm " + this.name);
    $('body').append(this.node);
};

// Define the CharWidget constructor
function CharWidget(node, name) {
  // Call the parent constructor, making sure (using Function#call)
  // that "this" is set correctly during the call
  Widget.call(node, name);

  // Initialize our Student-specific properties
  this.subject = subject;
};

// Create a CharWidget.prototype object that inherits from Widget.prototype.
// Note: A common error here is to use "new Widget()" to create the
// CharWidget.prototype. That's incorrect for several reasons, not least 
// that we don't have anything to give Widget for the "name" 
// argument. The correct place to call Widget is above, where we call 
// it from CharWidget.
CharWidget.prototype = Object.create(Widget.prototype); // See note below

// Set the "constructor" property to refer to CharWidget
CharWidget.prototype.constructor = CharWidget;

// Replace the "render" method
Student.prototype.render = function(){ 
    $(this.node).val(this.name); 
    $('body').append(this.node); 
};

// Add a "format" method
Student.prototype.get_value = function(){
  console.log("Value of node is ", $(this.node).val());
};

// Example usage:
var char_widget = new CharWidget("<input type='text' name='test'></input>", "Hello World");
char_widget.render();   // "This will add input box into body and add value Hello World"
char_widget.walk();       // "I am walking!"
char_widget.get_value(); // "Hello World!"

// Check that instanceof works correctly
console.log(char_widget instanceof Widget);  // true 
console.log(char_widget instanceof CharWidget); // true

 

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.

Before going on to Encapsulation and Abstraction first we need to know what Data Hiding is and how can we achieve it in JavaScript. Date hiding is protecting the data form accessing it outside the scope. For example, In Session class we have User ID properties which should be protected. Let's see how to do it.  

function Session(uid){
    //this is private variable 
    var uid = uid;
    //public properties and functions
    return{ 
        timezone: "Asia/Calcutta", 
        language: "en-US", 
        getUid: function(){
            return uid;
        }
    } 
}
var session = new Session(); 
//this will get undefined 
//because it is private to Session
console.log(session.uid); 
//Will get uid value we using session's method to access its property
//funtion to get private data 
console.log(session.getUid());


Abstraction

Abstraction is a mechanism that allows you to model the current part of the working problem, either by inheritance (specialization) or composition. JavaScript achieves specialization by inheritance, and composition by letting class instances be the values of other objects' attributes.

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).
 
var foo = function () {};

// logs "foo is a Function: true"
console.log('foo is a Function: ' + (foo instanceof Function));

// logs "foo.prototype is an Object: true"
console.log('foo.prototype is an Object: ' + (foo.prototype instanceof Object));


Polymorphism

Just as 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, unless the two classes hold a parent-child relation (i.e. one inherits from the other in a chain of inheritance).

Person.prototype.getInfo = function(){
 return "I am " + this.age + " years old " +
    "and weighs " + this.weight +" kilo.";
};
 
function Employee(age,weight,salary){
 this.age = age;
 this.weight = weight;
 this.salary = salary;
}
Employee.prototype = new Person();
 
Employee.prototype.getInfo = function(){
 return "I am " + this.age + " years old " +
    "and weighs " + this.weight +" kilo " +
    "and earns " + this.salary + " dollar.";  
};
 
var person = new Person(50,90);
var employee = new Employee(43,80,50000);

console.log(person.getInfo());
console.log(employee.getInfo());   


For detail go through: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

Your inputs are welcomed to improve this post.

Tuesday 21 April 2015

Grunt

What is grunt ?

 Grunt is a task-based command line build tool for JavaScript projects. Here's the idea: when working on a JavaScript project, there are a bunch of things you'll want to do regularly.

To check more details you can go through: http://gruntjs.com/
Getting started: http://gruntjs.com/getting-started


To install grunt just run the command sudo npm install -g grunt
Assuming you have nodejs and npm is installed.

for Grunt's command line interface, you need to install grunt-cli
npm install -g grunt-cli

This will put the grunt command in your system path, allowing it to be run from any directory.
Note that installing grunt-cli does not install the Grunt task runner! The job of the Grunt CLI is simple: run the version of Grunt which has been installed next to a Gruntfile. This allows multiple versions of Grunt to be installed on the same machine simultaneously.

Preparing a new Grunt project

A typical setup will involve adding two files to your project: package.json and the Gruntfile.
package.json: This file is used by npm to store metadata for projects published as npm modules. You will list grunt and the Grunt plugins your project needs as devDependencies in this file.
Gruntfile: This file is named Gruntfile.js or Gruntfile.coffee and is used to configure or define tasks and load Grunt plugins. When this documentation mentions a Gruntfile it is talking about a file, which is either a Gruntfile.js or a Gruntfile.coffee.

package.json
To create package.json file you just need to run the command npm init
This will prompt you with some questions (https://docs.npmjs.com/cli/init) provide the details and that's it.

As I specified that this file will contain development dependency of grunt and gruntPlugins, to install grunt plugin and also register it in package.json

npm install <module> --save-dev

For Example: npm install jquery --save-dev

npm install grunt --save-dev
npm install grunt-contrib-jshint --save-dev
npm install grunt-contrib-sass --save-dev
npm install grunt-contrib-watch --save-dev
 
This will install jquery inside node_modules  folder and will add dependecy in package.json


The Gruntfile

The Gruntfile.js or Gruntfile.coffee file is a valid JavaScript or CoffeeScript file that belongs in the root directory of your project, next to the package.json file, and should be committed with your project source.
A Gruntfile is comprised of the following parts:
  • The "wrapper" function
  • Project and task configuration
  • Loading Grunt plugins and tasks
  • Custom tasks

An example Gruntfile

In the following Gruntfile, project metadata is imported into the Grunt config from the project's package.json file and the grunt-contrib-uglify plugin's uglify task is configured to minify a source file and generate a banner comment dynamically using that metadata. When grunt is run on the command line, the uglify task will be run by default.
Say for example I am having all my static files(js, css inside staitc -> src directory)

module.exports = function(grunt) {

    grunt.initConfig({
        jshint: {
            src: ['static/src/**/*.js', 'static/test/**/*.js'],
            options: {
                sub: true, //[] instead of .
                evil: true, //eval
                laxbreak: true, //unsafe line breaks
            },
        },
        sass: {
            dev: {
                options: {
                    style: "expanded",
                },
                files: {
                    "static/src/css/base.css": "static/src/css/base.sass",
                }
            }
        },
        watch: {
            sass: {
                files: ["static/src/css/base.sass"],
                tasks: ['sass']
            },
        }
    });

    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');

    grunt.registerTask('gen', ["sass"]);
    grunt.registerTask('watcher', ["gen", "watch"]);
    grunt.registerTask('test', []);

    grunt.registerTask('default', ['jshint']);

};

The wrapper function

module.exports = function(grunt) {
  // Do grunt-related things in here
};

 
Every Gruntfile (and gruntplugin) uses this basic format, and all of your Grunt code must be specified inside above function.

Project and Task Configuration

Most Grunt tasks rely on configuration data defined in an object passed to the grunt.initConfig method.
In this example, we uses jshint plugin of grunt and providing paths of JS files

Loading Grunt plugins and tasks

Many commonly used tasks like concatenation, minification and linting are available as grunt plugins. As long as a plugin is specified in package.json as a dependency, and has been installed via npm install, it may be enabled inside your Gruntfile with a simple command:

// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-jshint');
 
 

Custom tasks

You can configure Grunt to run one or more tasks by default by defining a default task. In the following example, running grunt at the command line without specifying a task will run the 'jshint' task. This is functionally the same as explicitly running grunt jshint or even grunt default. Any number of tasks (with or without arguments) may be specified in the array.

 grunt.registerTask('default', ['jshint']);

If your project requires tasks not provided by a Grunt plugin, you may define custom tasks right inside the Gruntfile. For example, this Gruntfile defines a completely custom default task that doesn't even utilize task configuration:

module.exports = function(grunt) {

  // A very basic default task.
  grunt.registerTask('default', 'Log some stuff.', function() {
    grunt.log.write('Logging some stuff...').ok();
  });

};
 
Custom project-specific tasks don't need to be defined in the Gruntfile; they may be defined in external .js files and loaded via the grunt.loadTasks method.


 After all this configuration, creation of project, adding package.json and Gruntfile.js, defining initConfig and grunt plugin and tasks you just need to run grunt command

The output expected:
$ grunt
Running "jshint:src" (jshint) task
>> 1 file lint free.

Done, without errors.


To run specific task, you can also run grunt command with argument,
$ grunt test

Where test is registered task in grunt.

Monday 20 April 2015

Bower

What is bower ?

A very good explaining video about what is bower is here: https://egghead.io/lessons/bower-introduction-and-setup.

bower is a package manager to install JS packages, it also maintains dependency graph.

To install bower itself:
sudo apt-get install nodejs
sudo apt-get install npm
sudo npm install -g  bower

To install packages through bower: bower install jquery

to make your own bower.json: just load all packages at your end and just run bower init

This will ask some prompt, go through and that's it, your bower.json is prepared.

You can register your package on github through

bower register give_package_name 'your repository on github'