Scott Keck-Warren
Scott Keck-Warren

Reputation: 1952

Calling class functions from class functions in Javascript

I hate that I'm doing this but I've just started working with Javascript classes and I can't figure out how to call member functions from member functions. Below is the class I have and when I run this I get the following error in Firefox:

this.addCol is not a function

I've also tried calling the function like this:

Table.prototype.addCol(this,key,value);

but that also didn't work. :-)

Table.prototype.addCol = function(key, values){
    this.jquery.children('.columns').append('<li>' + key + '</li>');
}

Table.prototype.setData = function(data){
    // store the data for this table
    this.data = data;

    $.each(data.columns, function(key, value){
        this.addCol(key, value);
    });
}

function Table (name){
    this.name = name;

    this.jquery = $('<div class="dbtable"><h3>' + this.name + '</h3></div>');
}

Upvotes: 1

Views: 650

Answers (2)

SeanCannon
SeanCannon

Reputation: 78016

JavaScript has prototypal inheritance, not classical inheritance. There are no "classes" in JS. Using the "new Foo()" syntax in JS just sucks. It wasn't built to support that style of coding well.

That being said, there is a major design flaw in which a nested function inside an object will rebind this to the global object. In this case, this gets re-bound to the item in the $.each iteration.

There is a common workaround:

Table.prototype.setData = function(data){
    var that = this;
    // store the data for this table
    this.data = data;

    $.each(data.columns, function(key, value){
        that.addCol(key, value);
    });
}

Upvotes: 5

Adam Mihalcin
Adam Mihalcin

Reputation: 14478

Why not define the class as

function Table (name){
    this.name = name;

    this.jquery = $('<div class="dbtable"><h3>' + this.name + '</h3></div>');

    this.addCol = function(key, values){
        this.jquery.children('.columns').append('<li>' + key + '</li>');
    }

    this.setData = function(data){
        // store the data for this table
        this.data = data;

        $.each(data.columns, function(key, value){
            this.addCol(key, value);
        });
    }
}

in the first place?

Upvotes: 0

Related Questions