Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / JScript / July 2006

Tip: Looking for answers? Try searching our database.

JavaScript class creation query

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Dhruba Bandopadhyay - 10 Jul 2006 17:04 GMT
I have came across 3 different ways of creating a structure or class.

1. Class as a function way

// Class Constructor
function Timer(Source) {

// Class Properties
this.timerID = 0;
this.tStart = null;

// Class Methods
this.UpdateTimer = function() {
};
}

// Example
var timer = new Timer(0);
timer.UpdateTimer();

2. Class.create & prototype way

var WindowDelegate = Class.create();
WindowDelegate.prototype = {
// Class Constructor
initialize: function() {
},
canClose: function(win) {
}
}

3. Declare as a var way

var myObserver = {
variable: null,
anotherVariable: 33
stringVariable: 'asdf',
aFunction: function(a, b) {
}
}

I assume #3 is just a object/structure instance rather than a class
definition.

Has anyone came across #1 way? What are the differences between these 3
ways?
And what is the proper way to define a class?
Igor Tandetnik - 10 Jul 2006 17:42 GMT
> I have came across 3 different ways of creating a structure or class.
>
[quoted text clipped - 11 lines]
> };
> }

It's better to define a method like this:

function Timer() {...}
Timer.prototype.UpdateTimer = function() {...};

This way the function is created only once. In your original code, an
instance of the function object is created anew every time an instance
of Timer is created.

> 2. Class.create & prototype way
>
> var WindowDelegate = Class.create();

I've never seen this syntax. In IE, it produces an error " 'Class' is
undefined".

> 3. Declare as a var way
>
[quoted text clipped - 10 lines]
>
> Has anyone came across #1 way?

All major JavaScript libraries I know of do it this way. See e.g.
http://dojotoolkit.org/

> What are the differences between these
> 3 ways?

Well, #2 does not work. #1 has a nice encapsulated syntax, constructors
with parameters - you can almost pretend you are working in an object
oriented language. #3 is useful for a quick one-off object, but this
approach does not lend itself to reuse. Also, an object created with #1
can be tested with instanceof operator:

var timer = new Timer(0);
if (timer instanceof Timer) {...};

#3 also does not allow one to use prototype property to create a method
just once: you have to define it every time you create an instance,
which adds performance overhead. One can work around it like this, but
it's not as clear as #1:

function Timer_UpdateTimer() {...};
function makeTimer(source) {
   var timer = {};

   // Class Properties
   timer.timerID = 0;
   timer.tStart = null;

   // Class Methods
   timer.UpdateTimer = Timer_UpdateTimer;
}
var timer = makeTimer(0);

Almost everything you can do with #1 you can also do with #3, but I feel
#1 syntax is cleaner. The two things you can only achieve with #1 are
support for instanceof, and inheritance (in JavaScript, you can arrange
for one class to "inherit" from another, several levels deep; multiple
inheritance is not really supported, but there are techniques to fake
it).

> And what is the proper way to define a class?

#1.
Signature

With best wishes,
   Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925

Anthony Jones - 11 Jul 2006 09:19 GMT
> > I have came across 3 different ways of creating a structure or class.
> >
[quoted text clipped - 86 lines]
>
> #1.

There are ultimately two 'proper' ways to define a class as you have already
touched on.  To clarify:-

Option A.

function MyClass(value)
{
   var x = 0, y = 0  //private class level variables

   this.a = value  // public member

   function fnPrivateStuff()  // private functions
   {
   ...
   }

   this.publicStuff = function()  // public method
   {
   ...
   }

}

This approach provides much stronger encapsulation (x,y for example can only
be referenced from a function defined inside the class) it is therefore more
suited to large complex objects.   However as pointed out instances of this
type are more expensive to create so may not be the best choice if a large
number are to be created.  A more important point IMO is that implementing a
design that incoporates generalised and specialised classes (inheritance) is
awkward in this approach.

Option B

function MyClass(value)
{
   this.x = 0; this.y = 0
   this.a = value
}
MyClass.prototype.fnPrivateStuff = function()
{

}
MyClass.prototype.publicStuff = function()
{

}
MyClass.prototype.publicStuff2 = function()
{

}

This approach has much weaker encapsulation.  In fact it has no
encapsulation at all.  The distinction between public and private members
would have to rely on conventions such as the use of a preceeding underscore
in member names.  Creating a large number of instances of this class is
cheaper since the created instance only needs to carry the value the member
variables not the functions.  This approach's biggest strength is in
implementing specialisation of general classes:-

function MyDerivedClass(value1, value2)
{
   MyClass.call(this, value1)  //Base class constructor
   this.b = value2
}
MyDerivedClass.prototype = new MyClass()
MyDerivedClass.prototype.somePublicMethod = function()
{

}
MyDerivedClass.prototype.publicStuff2 = function() // override
{

}

On thing often missed in the prototype approach is that default values for
non-function members can also be defined.  This further reduces the cost of
creating instances of these classes where member values are only actually
created when a new value is assigned to them.   The MyClass above can look
like this:-

function MyClass(value)
{
   this.a = value
}
MyClass.prototype.x = 0
MyClass.prototype.y = 0

HTH,

Anthony
Peter Torr (MS) - 12 Jul 2006 15:57 GMT
> Has anyone came across #1 way? What are the differences between these 3
> ways?

I recently made two fairly detailed posts about this on my blog:

http://blogs.msdn.com/ptorr/archive/2006/06/13/630208.aspx

http://blogs.msdn.com/ptorr/archive/2006/06/19/638195.aspx

A third is on the way...

> And what is the proper way to define a class?

Tecnically these are not classes and there is no "right" or "wrong" way of
doing it -- if the interpreter doesn't blow up, clearly you've done
something right :-)

Peter

Signature

Peter Torr - http://blogs.msdn.com/ptorr
HD DVD Program Manager

asdf - 19 Jul 2006 10:17 GMT
Net neutrality
class free society
school is over (that one was deleted by ms)

We don't want to be "classified" as lusers, users or idiots.
--------------------------------------------
The net as is, is a keeper.

We paid for it for 10 years plus.

We own it.

We shall cause uncomfort to anyone,
tresspassing our ways and means and believes
of the Internet as is.

Never without our consent.

We don't want an iraque modell of conquest
to hush potentil progress other than fuzzy Texan business laws..
--------------
Let the old guys the US Congress know that !

=========================

I am not a Bush fan, but I know when he rides a bike,
he is clear in his mind.

He just does not understand to communicate beyond his
education.

.

> > Has anyone came across #1 way? What are the differences between these 3
> > ways?
[quoted text clipped - 14 lines]
>
> Peter
asdf - 19 Jul 2006 10:35 GMT
correction

" than fuzzy Texan business laws.."

should be

"hurting fuzzy Texan business laws.."

> Net neutrality
> class free society
[quoted text clipped - 47 lines]
> >
> > Peter

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.