Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top