Thursday, May 2, 2013

Anonymous Classes in JavaScript

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once. Below example will explain how to create anonymous class/object(actually javaScript is prototype based language)

var a = new (function(name){ this.name = name;
                     this.sayHello = function(){
                    console.log("Hello, ", this.name, "!");
               };})("Jason");
//Adding new method after creation

a.constructor.prototype.sayGoodbye = function(){
    console.log("Goodbye, ", this.name,".");
};
a.sayHello();
a.sayGoodbye();

Anonymous classes can be useful for things like mock objects in the case of unit tests. Imagine that you have a unit test which checks that a static method called serialize() correctly serializes an instance of its class, MyClass to a JSON string. We don’t really want to create a new instance of the real class if we only need to check that certain attributes are correctly serialized.

For creating anonymous class in ExtJS 4 we need to pass blank class name below example explain it:


Ext.define(null, {
     constructor: function () {
         // ...
     }
 });

No comments:

Post a Comment