Monday, January 6, 2014

Some Useful Basic Different ways of Javascript Coding

Style 1 Procedural Way

/* Start and stop animations using functions. */

function startAnimation() {


}

function stopAnimation() {


}

Style 2: using Prototype to define Class function

/* Anim class. */

var Anim = function() {


};

Anim.prototype.start = function() {


};

Anim.prototype.stop = function() {


};

/* Usage. */

var myAnim = new Anim();

myAnim.start();

myAnim.stop();

Style 3: Encapsulated Prototyping

/* Anim class, with a slightly different syntax for declaring methods. */

var Anim = function() {


};

Anim.prototype = {

                start: function() {

               …

              },

               stop: function() {

              …

 }

};

Style 4: Function.prototype.method

/* Add a method to the Function object that can be used to declare methods. */

Function.prototype.method = function(name, fn) {

                this.prototype[name] = fn;

};

/* Anim class, with methods created using a convenience method. */

var Anim = function() {


};

Anim.method(‘start’, function() {


});

Anim.method(‘stop’, function() {


});



Style 5: Chain Function Approach

/* This version allows the calls to be chained. */

Function.prototype.method = function(name, fn) {

                     this.prototype[name] = fn;

                    return this;

};

/* Anim class, with methods created using a convenience method and chaining. */

var Anim = function() {


};

Anim.method(‘start’, function() {


})

.method(‘stop’, function() {


});
Post a Comment