Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Three ways to define class in JavaScript

  é˜®ä¸€å³°        2012-07-09 11:59:51       11,766        0    

In object oriented programming, class is the template of object, it defines the properties and methods of a group of objects. Unfortunately, JavaScript doesn't support class, but we can have some workarounds to simulate class.

1. Constructor function

This is the classical approach, it is also the approach mentioned in many text books. It uses the constructor function to simulate class and it uses the keyword this to represent the object internally.

function Cat() {
  this.name = "Kelly";
}

when creating the instance, use the new keyword.

var cat1=new Cat();
alert(cat1.name); //Kelly

The properties and methods of the class can also be defined use the class's prototype object.

Cat.prototype.makeSound = function(){
    alert("Miau-miau-miau");
}

The main drawback of this approach is that it is a bit complex since it uses the this and prototype.

2. Object.create()

To avoid the drawback of the constructor function approach. The JavaScript standard ECMAScript 5th edition introduced a new method named Object.create().

With this method, class is an object, not a function.

      var Cat = {
    name: "Kelly",
    makeSound: function(){ alert("Miau-miau-miau"); }
      };

Then you can use Object.create() to create the new instance without using the keyword new.

 var cat1 = Object.create(Cat);
 alert(cat1.name); // Kelly
 cat1.makeSound(); // Miau-miau-miau

Currently all the major browsers(including IE9) have implemented this method. If you have an old browser, you can use following code to achieve this.

 if (!Object.create) {
    Object.create = function (o) {
       function F() {}
      F.prototype = o;
      return new F();
    };
 }

This approach is simpler than the constructor function approach. But it cannot have the private property and private method. You cannot share data among different instances, either.

3. Minimalist approach

Netherlands programmer Gabor de Mooij proposed an approach which is better than the Object.create() approach, it is called minimalist approach.

3.1. Encapsulation

This approach doesn't use this and prototype, it's very easy to implement. First, it uses an object to simulate a class, in this class, you define a constructor function named createNew() to create the new instance.

       var Cat = {
    createNew: function(){
      // some code here
    }
  };

then in the createNew(), you create an object and return this object.

    var Cat = {
    createNew: function(){
      var cat = {};
      cat.name = "Kelly";
      cat.makeSound = function(){ alert("Miau-miau-miau"); };
      return cat;
    }
  };

when in use, you only need to call the createNew() method , then you can get the object created.

        var cat1 = Cat.createNew();
  cat1.makeSound(); // Miau-miau-miau

the advantages of this approach are it is easy to understand and its structure is very clear.

3.2 Inheritance

It is very simple to have one class to extend another class. You only need to call the base class's createNew() method in the derived class's createNew() method. First, define an Animal class.

       var Animal = {
    createNew: function(){
      var animal = {};
      animal.sleep = function(){ alert("Sleep"); };
      return animal;
    }
  };

Then in Cat's createNew() method, call the Animal's createNew() method.

       var Cat = {
    createNew: function(){
      var cat = Animal.createNew();
      cat.name = "Kelly";
      cat.makeSound = function(){ alert("Miau-maiu-miau"); };
      return cat;
    }
  };

The Cat object now will have both Cat's and Animal's properties and methods.

        var cat1 = Cat.createNew();
  cat1.sleep(); // Sleep

3.3 Private property and private method

In createNew(), any property or method which is not defined on Cat will be private.

       var Cat = {
    createNew: function(){
      var cat = {};
      var sound = "Miau-miau-miau";
      cat.makeSound = function(){ alert(sound); };
      return cat;
    }
  };

The sound variable defined in createNew() cannot be accessed from a Cat object. You can only access it through the public method makeSound() of Cat.

     var cat1 = Cat.createNew();
  alert(cat1.sound); // undefined

3.4 Data share

Sometimes we may need all objects of a class to access the same block of data. What we need to do is putting the variable out of createNew() method.

        var Cat = {
    sound : "Miau-miau-miau",
    createNew: function(){
      var cat = {};
      cat.makeSound = function(){ alert(Cat.sound); };
      cat.changeSound = function(x){ Cat.sound = x; };
      return cat;
    }
  };

Now create two objects.

        var cat1 = Cat.createNew();
  var cat2 = Cat.createNew();
  cat1.makeSound(); // Miau-miau-miau

if an object modifies the sound, other objects will be affected.

        cat2.changeSound("La-la-la");
  cat1.makeSound(); // La-la-la

Finally, you can also find an approach for JavaScript object inheritance written by John Resig: http://ejohn.org/blog/simple-javascript-inheritance/

Author : 阮一峰 Source : http://www.ruanyifeng.com/blog/2012/07/three_ways_to_define_a_javascript_class.html

JAVASCRIPT  METHOD  CLASS  INHERITANCE  PRIVATE 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.