JavaScript is used as a simple scripting engine to create dynamic web pages. Modern web designers have come to use more object oriented techniques in JavaScript programming.
The current design of the JavaScript language does not fully implement an object oriented system. That is many various ways of implementations and techniques being used on the web today.
Simple Objects
The simplest way to use is the built-in Object data type. In JavaScript, objects are implemented as a collection of named properties. Being an interpreted language, JavaScript allows for the creation of any number of properties in an object at any time (unlike C++, properties can be added to an object at any time; they do not have to be pre-defined in an object declaration or constructor).
var obj = new Object; obj.var1 = 1; obj.var2 = 2; |
Object Constructors
A new JavaScript class is defined by creating a simple function. When a function is called with the new operator, the function serves as the constructor for that class. Internally, JavaScript creates an Object, and then calls the constructor function. Inside of the constructor, the variable ‘this’ is initialized to point of the just created Object. The code snippet below defines a new class, Foo, and then creates a single object of that class.
function Foo() {
this.var1 = 1;
this.var2 = 2;
}
obj = new Foo; |
Defining and Calling Methods in a Class
JavaScript allows you to assign any function to a property of an object. When you call that function using obj.Function() syntax, it will execute the function with ‘this’ defined as a reference to the object.
function Foo() {
this.var1 = 1;
}
Foo.prototype.Add = function(var2) {
this.var1 += var2;
}
obj = new Foo;
obj.Add(5); // obj.var1 = 6 |
Private Members
JavaScript also can support private members in an object. When the constructor is called, variables declared in the function scope of the constructor will actually persist. They will stay beyond the lifetime of the construction function itself. To access these variables, you only need to create local functions within the scope of the constructor. They may reference local variables in the constructor.
function Foo() {
var value = "Hello";
this.GetValue = function() { return value;}
this.SetValue = function(newValue) { value = newValue; }
}
obj = new Foo;
obj2 = new Foo;
obj2.SetValue("World!");
alert(obj.GetValue() + ' ' + obj2.GetValue()); // "Hello World!" |
Since the benefits of using private members is rather limited in the context of JavaScript, I would not recommend making extensive use of the private member paradigm.
Linux training
If you need to improve your skills try my linux training guide, read more
