Uncaught ReferenceError: "method" is not defined

julian384 picture julian384 · Aug 4, 2014 · Viewed 6.9k times · Source

I've created a javascript object

var Article = function(data) {
    this.foo = data,
    this.get_more_data = function() {
        // do something, get a response
        show_data(response);
    },
    this.show_data = function(bar) {
        //do something with bar;
    }
};

which works fine when the method show_data is written without this. but then it isn't accessible outside of the object. With this. I get a "Uncaught ReferenceError" from the Chrome console.

Why is this?

Thanks.

Answer

Rob M. picture Rob M. · Aug 4, 2014

You should be calling show_data as a method of this, not as a function scoped to the current context:

var Article = function(data) {
    this.foo = data,
    this.get_more_data = function() {
        // do something, get a response
        this.show_data(this.foo);
    },
    this.show_data = function(bar) {
        console.log(bar);
    }
};