Wednesday, August 3, 2011

Fluent Interface Implementation in Javascript

I mentioned  Fluent Interface in  C#   in my previous entry. You can design your classes in JavaScript in the same way.

Most popular example of Fluent Interface in JavaScript is jQuery. I think this is the best reason why jQuery is widely chosen to other JavaScript frameworks. In jQuery you can easily call methods in same line. It's readable and easy to comprehend what code does.

Following code example shows how to design your javascript classes to provide fluent interface technique. If you look at carefully, in each method this keyword which represents current instance of the class is returned.

It's the same class design example of Car in previous entry.

   1:  var Car = function () {
   2:      var Color, EngineType;
   3:   
   4:      this.setColor = function (color) {
   5:          this.Color = color;
   6:          return this;
   7:      }
   8:   
   9:      this.setEngineType = function (engineType) {
  10:          this.EngineType = engineType;
  11:          return this;
  12:      }
  13:   
  14:      this.StartUp = function () {
  15:          alert("Started up");
  16:          return this;
  17:      }
  18:   
  19:      this.DriveTo = function (direction) {
  20:          alert("Driving to " + direction);
  21:          return this;
  22:      }
  23:      this.SetSpeed = function (speed) {
  24:          alert(speed + " km per hour");
  25:          return this;
  26:      }
  27:   
  28:      this.PullOver = function () {
  29:          alert("Pulled over");
  30:          return this;
  31:      }
  32:  }
  33:  function initCar() {
  34:      car = new Car();
  35:      car.setColor("Black")
  36:                  .setEngineType("Diesel")
  37:                  .StartUp().DriveTo("south")
  38:                  .SetSpeed(90).PullOver();
  39:   
  40:      document.getElementById("result").innerText = "color of the car is " + 
  41:                  car.Color + " and engine type is " + car.EngineType;
  42:  }

At line 34; I created instance of Car class
At line 35; I called methods in order to set values and run the statements in them.
At line 40; I wrote the values of property of Car instance class on page.

Output :
color of the car is Black and engine type is Diesel 

0 comments: