Online
 
Friday, 21 November 2008
 
 

JavaScript - Object-Oriented JavaScript | Print |  E-Mail
 

Object-Oriented JavaScript

JavaScript objects are associative arrays that associate values with named properties. JavaScript provides a simple inheritance mechanism, and it is possible to define new classes of objects for use in your own programs. To define a new class, start by writing a constructor function. A constructor is like any other function, except it is invoked with the new operator and it uses the this keyword to refer to and initialize the newly created object. For example, here is a constructor to create objects of a new class named Point.

function Point(x,y) { // Constructor for Point

this.x = x; // Initialize X coordinate

this.y = y; // Initialize Y coordinate

}

Every JavaScript function used as a constructor has a property named prototype. This property refers to a special prototype object for the class of objects created by the constructor. Any properties you define on this prototype object are inherited by all objects created with the constructor function. The prototype object is commonly used to make methods available to all instances of a class. Defining a method named toString allows instances of your class to be converted to strings. For example:

// Define function literals and assign them 

// to properties of the prototype object.

Point.prototype.distanceTo = function(that) {

var dx = this.x - that.x;

var dy = this.y - that.y;

return Math.sqrt(dx*dx + dy*dy);

}

Point.prototype.toString = function () {

return '(' + this.x + ',' + this.y + ')';

}

If you want to define static (or class) methods or properties, you can assign them directly to the constructor function, rather than to the prototype object. For example:

// Define a commonly used Point constant

Point.ORIGIN = new Point(0,0);

The preceding code fragments define a simple Point class that we can use with code like this:

// Call constructor to create a new Point object

var p = new Point(3,4);

// Invoke a method of the object, using a static

// property as the argument.

var d = p.distanceTo(Point.ORIGIN);

// Adding the object to a string implicitly

// invokes toString().

var msg = "Distance to " + p + " is " + d;

 

 

This entry was posted on . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a comment.
Users' Comments (0)

Comment an article
  Name
  E-mail
   Title
Available characters: 4000
 Notify me of follow-up comments
This image contains a scrambled text, it is using a combination of colors, font size, background, angle in order to disallow computer to automate reading. You will have to reproduce it to post on my homepage
Enter what you see:

No comment posted

Rokok Kretek Jumbo Coklat

“Terbuat dari tembakau, saos dan cengkeh pilihan kwalitas tinggi sehingga menghasilkan rokok dengan rasa yang cocok untuk segala cuaca”
Jumbo Coklat - Powered By G-Ads

 
Top! Top!