0

I recently started JavaScript and I am having trouble with the classless OOP style it uses. Here is an example of an object I am trying to use:

function block(id, text, distance) {
    this.id = id;
    this.text = text;
    this.distance = distance;

    this.getId = function () { return this.id };
    this.getText = function () { return this.text };
    this.getDistance = function () { return this.distance };
    this.addDistance = function (Distance) { this.distance = this.distance + Distance };
}

However this doesn't seem to work. I then did some reading here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects, which seemed to suggest I remove the methods from my function and add them using the prototype object of my block:

block.prototype.getDistance = function () {
    return this.distance;
};

block.prototype.addDistance = function (Distance) {
    this.distance = this.distance + Distance;
};

But this still doesn't seem to work. For example if I am trying to loop through an array of blocks and add up the distance:

var distTot = 10;
for (var i = 1; i < blocks.length; i++) {
   var set = setLarge[i];

   distTot = distTot + blocks[i - 1].getDistance;
};

I end up with the following as the contents for the distTot variable: "10function () {\r\n return this.distance;\r\n }function () {\r\n return this.distance;\r\n }"

Could any one please explain to me what I am doing wrong? I have checked to see that they are being instantiated correctly and everything seems fine there. I am pretty sure it is just the methods that are not working correctly. Thanks in advance!

2
  • The prototype and the this code should both work. Can you please show us how you are instantiating your block objects, how you call the constructor? Btw, you forgot to invoke the getDistance method. Commented Jan 16, 2014 at 11:53
  • @Bergi it seems that not instantiating the getDistance method was the problem, thanks! Commented Jan 16, 2014 at 12:05

2 Answers 2

1

When you call a function, you should add (), so try getDistance() instead of just getDistance

Sign up to request clarification or add additional context in comments.

1 Comment

Oh wow! So silly of me. Thanks very much for the help. Ill accept this answer as soon as my 9 minutes are up!
1

getDistance is a function so you should call it as a function here

distTot = distTot + blocks[i - 1].getDistance();

otherwise, as you've noticed, you obtain the string representation of the function itself

1 Comment

Thanks, I didn't understand the difference between calling the function and getting its string value before!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.