Object Oriented JavaScript–Class Method

Recently I am implementing 3D rendering in JavaScript. Professor Saty Raghavachary gave me a very good introduction of JavaScript class/methods, which helped me get much better understanding of JavaScript’s power and flexibility.

There are four ways to declare a method of a class

    1. As a member of the class declared inside constructor:
      see example

      function Vector(x,y,z){
         this.x = x;
         this.y = y;
         this.z = z;
         //don't do it this way
         //this.normalize = function(){...};
      }
      

      The downside is every instance of the class would create its normalize method, which is unnecessary and redundant. This is a bad choice, don’t do it this way. Only include data/variables in constructor.

    2. As a class level static method:
      see example (assume we already have Vector class)

      Vector.unit = function(){ return new Vector(1,0,0) }
      

      This will create a static method, which is object independent.

    3. As a prototype method:
      see example (assume we already have Vector class)

      Vector.protoype.normalize= function(){ ... };
      

      By calling prototype, the method is attached to a prototype, and every instance of the Vector class has a pointer to the same prototype, thus can call this method from there. This is the right way to do it, since we only need one copy of the method. One magic thing about prototype is its method can be added even after some instances are declared, and still usable to that instance, see example:

      var obj = new Vector(1,0,0);
      Vector.prototype.addMethod = function(){...};
      obj.addMethod();
      

      Another even more incredible thing is other class can also add the same method by pointing to it. Say we have another class Normal, we can assign Normal.prototype.normalize = Vector.prototype.normalize, to point to normalize method of Vector. By doing this, we can actually mix&match classes/methods, and break class inheritance restrictions.

    4. As a private method only owned by one instance:
      See example:

      var a = Vector(0,0,1);
      a.aMethod = function(){...};
      a.aMethod();
      

      In this case, the aMethod is a private method owned only by a, so it can only be called by a, not by other instances. Also can use delete(a.aMethod) to remove the method after done with it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s