1

I am attempting to call a method of an object in a game, and I keep getting this error: "Uncaught TypeError: Object # has no method 'calculateDps'", Here's the relevant code:

    function Item(pBase, price){
        this.pBase = pBase;
        this.price = price;
        pMultiplier = 1;
        number = 0;

        calculateDps = function(){
            return this.pBase * pMultiplier * number;
        };
    };

    var cursor = new Item(.1,15);

    var calcDps = function(){
        return cursor.calculateDps();
    };

    calcDps();
  • Maybe the following answer will help out with understanding JavaScript prototype, object definition and creation http://stackoverflow.com/a/16063711/1641941 – HMR Feb 17 '14 at 10:36

1 Answers1

0
calculateDps = function(){
    return this.pBase * pMultiplier * number;
};

You are creating a global variable called calculateDps, since you are not using var keyword. In order to attach this to the current object being generated, you need to do

this.calculateDps = function(){
...

But the ideal way to do this would be to add the functions to the prototype, like this

function Item(pBase, price){
    this.pBase = pBase;
    this.price = price;
    this.pMultiplier = 1;
    this.number = 0;
};

Item.prototype.calculateDps = function() {
    return this.pBase * this.pMultiplier * this.number;
};

Now, calculateDps will be available to all the objects which are created with Item constructor function.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497