JavaScript

Moderators: None (Apply to moderate this forum)
Number of threads: 2059
Number of posts: 5157

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Object oriented Programming Posted by mac_doggie on 15 Oct 2002 at 6:48 AM
Hi,

I'm experimenting with object oriented programming in JavaScript and encountered something I don't understand. Hope someone can help me out here...

example
function MyObject(A,B) {
  this.A      = A;
  this.B      = B;
  this.SUM    = sum(this.A,this.B);
}

function sum(A,B) {
  return A+B;
}

var MyVar = new MyObject(10,10);

document.write(MyVar.A +'+'+ MyVar.B +'='+ MyVar.SUM+'<br>');
MyVar.A = 100;
document.write(MyVar.A +'+'+ MyVar.B +'='+ MyVar.SUM+'<br>');



With this piece of code I create a new instance of MyObject. I then want to calculate the sum of the two numbers A and B, so I call the function MyObject.SUM. fact is this function is only called once when calling the constructor. When I call the function MyObject.SUM it only display's the value it calculated before. When I change MyObject.A to 100 the sum still remains 20 when it should now be 110.

How do I make shore the function sum is called everytime I call MyObject.SUM ?

-mac-
mailto:programmersheaven@mac-doggie.nl
the Netherlands...

Report
Re: Object oriented Programming Posted by Anjuna Moon on 15 Oct 2002 at 8:14 AM
Hi, you need to define SUM as a method of the object, which is done in the line MyObject.prototype.SUM = sum; below.
Try this modified code Also note that SUM is called with SUM()
/Chris

function MyObject(A,B) {
this.A = A;
this.B = B;
}

function sum() {
return this.A+this.B;
}
MyObject.prototype.SUM = sum;

var MyVar = new MyObject(10,10);

document.write(MyVar.A +'+'+ MyVar.B +'='+ MyVar.SUM()+'<br>');
MyVar.A = 100;
document.write(MyVar.A +'+'+ MyVar.B +'='+ MyVar.SUM()+'<br>');




 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.