我讨厌我这样做,但我刚刚开始使用Javascript类,我无法弄清楚如何从成员函数调用成员函数。下面是我的类,当我运行它时,我在Firefox中收到以下错误:
this.addCol不是函数
我也尝试过调用这个函数:
Table.prototype.addCol(this,key,value);
但这也行不通。 : - )
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>');
}
答案 0 :(得分:5)
JavaScript具有原型继承,而不是经典继承。 JS中没有“类”。在JS中使用“new Foo()”语法很糟糕。它不是为了支持这种编码风格而构建的。
话虽如此,但是存在一个主要的设计缺陷,即对象内部的嵌套函数会将this
重新绑定到全局对象。在这种情况下,this
会重新绑定到$.each
次迭代中的项目。
有一个共同的解决方法:
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);
});
}
答案 1 :(得分:0)
为什么不将类定义为
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);
});
}
}
首先?