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!
thiscode should both work. Can you please show us how you are instantiating yourblockobjects, how you call the constructor? Btw, you forgot to invoke thegetDistancemethod.