Friday, March 29, 2013

JavaScript Object Oritented Programming Vs C# (C++, Java)


JavaScript's OOP model is very different from C# or C++, Java. If you are from a background of C#(Java) programmer, it would take a while to really understand and get used to the OOP concepts in JavaScript.

At first glance when you study the object, class and inheritance in JavaScript, they all looks very familiar and you think you could understand them easily but you may not.

One thing that took me quite a while to really understand is that in JavaScript there is no real "Class". (or in other words, the Class in JavaScript is very different from C#).

Another thing that can help you understand OOP in JavaScript is that JavaScript is very "Object Centric" vs C# is "Class Centric".

With C#, you start programming by defining "Classes" and create inheritance among "Classes". In JavaScript, you usually start with defining "Objects" and create inheritance between "Objects". "Class" in JavaScript is really just a special function called "Constructor" (another familiar concept but it is very different).

A third thing that can help your understanding is that almost everything in JavaScript is "Object", object is object, function is object, class is function so it is object, namespace is function so it is object, string is object, array is object, ...

Class in C#

using System;
public class Dog
{
    private string face, color, leg;
    public Dog(string face, string color, string leg)
    {
        this.face = face;
        this.color = color;
        this.leg = leg;
    }
 
    public virtual string Run()
    {
        return face + color + leg + " is running";
    }
 
    public string Name
    {
        get
        {
            return "Dog";
        }
    }
}
 
public class GoldenRetriever : Dog
{
    public GoldenRetriever(string face, string color, string leg): base(face, color, leg)
    {   
    }
 
    public override string Run()
    {
        return "Gollden Retriever " + base.Run();
    }
}
 
class Program
{
    static void Main(string[] args)
    {
        //Create an instance of Dog
        Dog myDog = new Dog("^_^""""# # # #");
        Console.Write(myDog.Run());
 
        //Create an instance of golden retriever
        GoldenRetriever myGoldenRetriever = new GoldenRetriever("^_^""yellow""@ @ @ @");
        Console.Write(myGoldenRetriever.Run());
    }
}
 
The C# example shows that in C#, you starts with define a class "Dog" then define another class "GoldenRetriever" inherits from it. After both classes are defined, you can create objects from them. So in C#, you say "GoldenRetriever" inherits from "Dog". They are all classes. You don't say "myGoldenRetriever" inherits from "myDog", since they are all objects.

However, in JavaScript you do say that "myGoldenRetriever" inherits from "myDog", since in JavaScript "myDog" is used as template to create another object "myGoldenRetriever". Inheritance happens between objects than classes.

Class in JavaScript

Actually it is easier to think JavaScript without thinking about class. In JavaScript when mentioning "Class", you are just mentioning a function which plays the role of constructor of object. In my opinion JavaScript is a "Object Oriented Lanuage" without "Class".

1. Create a "Class".

        // Dog class constructor
        function Dog(face, color, leg) {
            this.face = face; // smily face
            this.color = color;
            this.leg = leg; // four legs
        }
        Dog.prototype = {
            run: function () { return this.face + this.color + this.leg + " is running ..." },
            // object properties added in prototype
            name: "Dog"
        }

2. Create an object from the "Class".

            var myDog = new Dog("^_^""""# # # #");
 
            ShowMessage2("run 1:" + myDog.run());
            ShowMessage2("run 1:" + myDog.face);
 
3. Create an inherited object from another object using ECMAScript 5.
 
            var myGoldenRetriever1 = Object.create(myDog);
            myGoldenRetriever1.face = "^...^";
            myGoldenRetriever1.color = "yellow";
            ShowMessage2("run 2:" + myGoldenRetriever1.run());
            ShowMessage2("run 2:" + myGoldenRetriever1.color);
 
 4. Create an inherited object from another object without ECMAScript 5

        // Create new GoldenRetriever object inheriting from dog
        function CreateGoldenRetriever(dog) {
            // GoldenRetriever class constructor
            function GoldenRetriever() { };
            GoldenRetriever.prototype = dog;
            return new GoldenRetriever();
        }

            var myGoldenRetriever2 = CreateGoldenRetriever(myDog);
            myGoldenRetriever2.face = "^...^";
            myGoldenRetriever2.color = "golden";
            ShowMessage2("run 3:" + myGoldenRetriever2.run());
            ShowMessage2("run 3:" + myGoldenRetriever2.face);

5. Create an inherited object from another object without ECMAScript 5 in more generic way.

        // inherit() returns a newly created object that inherits properties from the
        // prototype object p. It uses the ECMAScript 5 function Object.create() if
        // it is defined, and otherwise falls back to an older technique.
        function inherit(p) {
            if (p == nullthrow TypeError(); // p must be a non-null object
            if (Object.create) // If Object.create() is defined...
                return Object.create(p); // then just use it.
            var t = typeof p; // Otherwise do some more type checking
            if (t !== "object" && t !== "function"throw TypeError();
            function f() { }; // Define a dummy constructor function.
            f.prototype = p; // Set its prototype property to p.
            return new f(); // Use f() to create an "heir" of p.
        }

            var myGoldenRetriever3 = inherit(myDog);
            ShowMessage2("run 4:" + myGoldenRetriever3.run());
            ShowMessage2("run 4:" + myGoldenRetriever3.face);

As you can see in any of aboves ways to do inheritance in JavaScript, a new object is created and inherites from an existing object "myDog". "myGolenRetreiver" inherits from "myDog" but it is not a "sub class" of "myDog" since they are all objects.

In JavaScript it is possible to introduce the concept of "sub class", the "sub class" in JavaScript is a way to create contructor function based on another contructor function. It is more advanced topic and I am not sure how practical to use it in the real world.

Here are few good articles that explains "prototype" in details.

http://msdn.microsoft.com/en-us/magazine/ff852808.aspx

http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/

http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/
 
 
 
 
 
 
 

No comments:

Post a Comment