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>');
}
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
thisto the global object. In this case,thisgets re-bound to the item in the$.eachiteration.There is a common workaround: