Object oriented Programming - Programmers Heaven

Howdy, Stranger!

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

Categories

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:[email protected]
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.