JavaScript is a nominally object-oriented language with extremely loose typing. However, it is possible to build objects which are based on class definitions, or prototypes in JavaScript parlance. Any object in JavaScript can have properties and methods attached to it—at any time. A prototype is nothing more than a function call which returns a generic object configured in a specific way.
Objects are created with the new operator; any function can be used as a constructor. Use the this property to access the object being constructed and to assign properties and methods to it. There are two ways to assign methods:
prototype keyword to define functions as belonging to a particular classWhen using a standard function, the function is connected to a particular name to create a method. When the function is called through the method, the this property is available within the function scope.
function MyClass (n)
{
this.Name = "MyClass__" + n;
this.PrintName = MyClassPrintName;
}
function MyClassPrintName ()
{
document.Write (this.Name);
}The prototype keyword offers a way of defining classes without cluttering the global namespace with functions.
function MyClass (n)
{
this.Name = "MyClass__" + n;
}
function MyClass.prototype.PrintName = function
{
document.Write (this.Name);
}The object can now be created and used with the expected syntax:
var obj = new MyClass ("Johann");
obj.PrintName ();With a little more effort, you can even have inheritance and method redefinition in JavaScript. See Inheritance in JavaScript for more information.