| 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 |
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. There is another approach which is commonly known as Anonymous Function in other programming languages:
var myObject = new function() { this.aVar = 15; this.aMethod = function() { alert("I'm a method of the object myObject." + "aVar: " + this.aVar); }; }
If we need multiple objects with the same type, then we have to use a constructor function and the new keyword. Name of constructor function will become the type of its objects. That said, the Anonymous Function above is an unnamed constructor function with the new keyword.
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();
Click on Run to see the alert panel.
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.