iNET Interactive - Online Advertising Agency
          
   Home    Authors    About    Login    Contact Us
   Search:   
Advanced Search     
  Articles

  ASP (26)
  ASP.NET (19)
  C and C++ (4)
  CFML (2)
  CGI and Perl (16)
  Flash (2)
  Java (7)
  JavaScript (28)
  PHP (92)
  MySQL (13)
  MSSQL (3)
  HTML (35)
  SEO (9)
  Visual Basic (12)
  CSS (13)
  SSI (5)
  XML (12)
  C# (14)

  Developer News

July 3, 2008
Poll: Which Web editor do you use?
About
 
July 3, 2008
Book Review: Head First JavaScript
WebReference.com
 
July 3, 2008
10 Things You Can Do With a Wiki
About
 
July 2, 2008
Web Host Reviews - 10 New Reviews
About
 
July 2, 2008
14 Reasons You Should Join a Social Network
About
 
July 1, 2008
Mark Boulton's Freelance Design Secrets
SitePoint
 
Courtesy of moreover.com
 
Want to receive new articles via e-mail? Click here!
/Home /JavaScript

Object Oriented Javascript 

  Views:    13910
  Votes:    5
by George Jempty 3/27/05 Rating: 

Synopsis:

A demonstration of data hiding in Javascript to prove that it is indeed a bona fide object-oriented language
Pages: firstback1 forwardlast
The Article

In order to properly implement "data hiding", the dimension property from the code on the previous page just needs to be defined differently, specifically with the keyword “var” rather than “this”, as follows:

function Square(size) {
var dimension = size;
this.area = size * size;
}

var object1 = new Square(4);
alert("Dimension: " + object1.dimension + "\nArea: " + object1.area);











This results in the following:



OK, so we can hide the dimension property. Can we still access it though? Sure. Modifying our code to provide an “accessor” method:


function Square(size) {
var dimension = size;
this.area = size * size;

this.getDimension = function() {
return dimension;
}

var object1 = new Square(4);
alert("Dimension: " + object1.getDimension() + "\nArea: " + object1.area);
}












Results in the following:



For the curious, the mechanism by which this is accomplished is called a "closure". Just like with object oriented programming in general though, we don't need to know how it is accomplished ("implementation details"), we just need to know how to use it ("interface"). 

Think of "this" within an object constructor as the "public" access modifier in other OO languages, and "var" as "private".  This would actually make Javascript MORE object oriented than PHP4 (though arguably less so than PHP5). 

Interestingly, Perl implements Object Orientation in much the same way as Javascript (via closures), with regard to which Foldoc says "
other languages, such as Perl and VB, permit, but do not enforce OOP."  Go ahead and add Javascript to the list too.
Pages: firstback1 forwardlast

Similar/related articles:


 
  Sponsors