| Author |
Sample JavaScript example
|
Arjun Reddy
Ranch Hand
Joined: Nov 10, 2007
Posts: 622
|
|
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: 56204
|
|
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...
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
|
 |
Arjun Reddy
Ranch Hand
Joined: Nov 10, 2007
Posts: 622
|
|
Thanks for replying Bibeault. I got it. Below code works fine now.
|
 |
Arjun Reddy
Ranch Hand
Joined: Nov 10, 2007
Posts: 622
|
|
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: 56204
|
|
|
Either way.
|
 |
Arjun Reddy
Ranch Hand
Joined: Nov 10, 2007
Posts: 622
|
|
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: 56204
|
|
|
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: 622
|
|
|
Ok. Thanks Bibeault.
|
 |
 |
|
|
subject: Sample JavaScript example
|
|
|