我讨厌我这样做,但我刚刚开始使用Javascript类,我无法弄清楚如何从成员函数调用成员函数.下面是我的类,当我运行它时,我在Firefox中收到以下错误:
this.addCol不是一个函数
我也试过调用这个函数:
Table.prototype.addCol(this,key,value);
Run Code Online (Sandbox Code Playgroud)
但那也行不通.:-)
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>');
}
Run Code Online (Sandbox Code Playgroud)
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);
});
}
Run Code Online (Sandbox Code Playgroud)