Javascript Concepts Simplified Part 1: Javascript Classes
June 3, 2010 2 Comments
While the Javascript language offers many of the constructs required for object-oriented programming, they remain largely unused. Today we’ll take a look at how to start with object-oriented programing in Javascript. by defining a class in Javascript. We’ll use the simple HTML file to call our script file,
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Hello Javascript!</title> <script type="text/javascript" src="MyScript.js"></script> </head> <body> Hello Javascript! </body> </html>
Now let’s create a class definition (in MyScript.js). Note that there is no ‘class’ keyword in Javascript, the class definition is just a function definition,
function MyClass() { // Public field this.aPublicField = "This is a public field of the type MyClass"; // Private field var aPrivateField = "This is a private field of the type MyClass"; // Public method this.aPublicMethod = function() { // Use the private method if (aPrivateMethod()) { return this.aPublicField; } else { return aPrivateField; } } // Private method function aPrivateMethod() { return true; } // Oops! We can expose the private field this.exposePrivateField = aPrivateField; // and the private method this.exposePrivateMethod = aPrivateMethod; } // Create an instance of MyClass using the ‘new’ keyword var myclass = new MyClass(); // Get the public field alert(myclass.aPublicField); // Call the public method alert(myclass.aPublicMethod()); // Call the private field – can’t get to them directly alert(myclass.exposePrivateField); alert(myclass.exposePrivateMethod());
So it’s pretty simple to create a class in Javascript. We can also create a runtime field for the class,
// Create an instance of MyClass var myclass = new MyClass(); // Create a field at runtime myclass.aRuntimeField = "This is a runtime field of the type MyClass"; // View the field value alert(myclass.aRuntimeField);
Pingback: Javascript Concepts Simplified « I.Net
Pingback: Javascript Concepts Simplified Part 3: Javascript and JSON « I.Net