Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sample JavaScript example

 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64837
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...


 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for replying Bibeault. I got it. Below code works fine now.

 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64837
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Either way.
 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64837
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok. Thanks Bibeault.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic