Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Object oriented Programming

mac_doggiemac_doggie Posts: 488Member
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
[code]
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+'
');
MyVar.A = 100;
document.write(MyVar.A +'+'+ MyVar.B +'='+ MyVar.SUM+'
');

[/code]

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...

Comments

  • Anjuna MoonAnjuna Moon Posts: 89Member
    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()+'
    ');
    MyVar.A = 100;
    document.write(MyVar.A +'+'+ MyVar.B +'='+ MyVar.SUM()+'
    ');

Sign In or Register to comment.