| Summary: Class Design |
| Author: Maxence Delannoy |
| Published: July 29, 2007 |
| Ext Version: 1.1 |
Languages: English Chinese French
|
Javascript is different from other object-oriented languages like C++, Java or PHP. It's not based on the concept of classes, but it uses a concept named prototype. It is useful to note that the term class appears often even though it isn't exactly correct. When you see class think object.
Contents |
Object creation Making an object in Javascript is very simple :
var myObject = { aVar: 15, aMethod: function() { alert("I'm a method of the object myObject." + "aVar: " + this.aVar); } }
You don't have to define a class and instantiate it to create an object. We are using here an object initializer. It's perfect in the case of a single object. If we need multiple objects with the same type, then we have to use a constructor function and the new keyword.
Using a Constructor Function There are no classes in Javascript, but constructors exist. You write a function and then you create an object with the new keyword.
// At first, we write an empty constructor for our class function myClass() { this.aVar = 15; this.aMethod = function() { alert("I'm a method of the object myObject."); } } // We make an instance of our class var A = new myClass(); // Display 15 alert(A.aVar); // 2nd instance var B = new myClass();
Screen Shot of FireFox + Firebug Click on Run to see the alert panel.
Share methods All instances of any class share a single prototype object. This is where functions and shared values should be placed:
// We define a method of the prototype object Ext.apply(myClass.prototype, { defaultClassName: "x-widget-class", sharedMethod: function() { alert("I'm a shared method") } }); // Display our message A.sharedMethod(); // Same message B.sharedMethod();
There is no method named sharedMethod in the myClass definition. Javascript looks for a method with this name in the prototype object of myClass and calls it if it exists.