aspose file tools*
The moose likes HTML, CSS and JavaScript and the fly likes Sample JavaScript example Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Sample JavaScript example" Watch "Sample JavaScript example" New topic
Author

Sample JavaScript example

Arjun Reddy
Ranch Hand

Joined: Nov 10, 2007
Posts: 629
Hi All,

Why does the following example not work? The class and the methods both are declared by the keyword function here in JavaScript? Please also look at the comments I have put, if they are right or wrong.





Thanks.


Be Humble... Be Nice.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61658
    
  67

Arjun Reddy wrote:Why does the following example not work?
Making us guess what "not working" means isn't conducive to getting your question answered.

However, I think I'm guessing that you somehow expect sum() to magically act as a "method".

Firstly, trying to think of JavaScript as having "classes" is an analogy that breaks down rapidly. JavaScript is prototype-based rather than class-based, and a functional rather than an OO language.

So if you want a function to act as a "method" of the constructor, it needs to be a property of the constructor -- either transient or prototyped.

So...



[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Arjun Reddy
Ranch Hand

Joined: Nov 10, 2007
Posts: 629
Thanks for replying Bibeault. I got it. Below code works fine now.

Arjun Reddy
Ranch Hand

Joined: Nov 10, 2007
Posts: 629
I however have one more question though.

The following codes both are giving the same output so why use prototype actually? because I read that prototype object is used to make sure all the instances of an object have same property value.

Code 1:




Code 2:



Thanks.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61658
    
  67

Either way.
Arjun Reddy
Ranch Hand

Joined: Nov 10, 2007
Posts: 629
Bear Bibeault wrote:Either way.


Ok, In this case we can do it either way but is there any other use of the prototype object?

Thanks.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61658
    
  67

The prototype is basically a blueprint from which new versions of instances created via the constructor will be copied. By placing something in the prototype, you guarantee it will be part of every instance. Adding it, ad hoc, in the constructor has the same outward effect just through a different mechanism.
Arjun Reddy
Ranch Hand

Joined: Nov 10, 2007
Posts: 629
Ok. Thanks Bibeault.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sample JavaScript example