从"构造函数调用原型方法"

时间:2014-09-15 21:55:44

标签: javascript oop constructor static

我正在尝试制作javascript"构造函数"打电话给其中一个原型方法。是否可以这样做?

以下是代码:

    function updateableTable($table, $rowTemplate,  dataObjects, getIDFromObject) // at some point add the ability to add event handlers.
{
    this.$rowTemplate = $rowTemplate;
    this.$tableBody = $j($table).children('tbody');
    this.rowsByID = {};
    this.dataObjectsByID = {};
    this.getIDFromObject = {};

    for(var dataObj in dataObjects)
    {
        addRow(dataObj);
    }

    return {}; // still has the protypical methods.
}

updateableTable.prototype.addRow = function(dataObject) {
    //alert('inside add row');
    var id = this.getIDFromObject(dataObject);
    // if (true === doesIdExist(i)) {
        // alert('id ' + id + ' already exists in table.');
        // return false;
    // }
    var newRow = $rowTemplate.tmpl(dataObject);
    this.rowsByID.add(id, newRow);
    this.dataObjectsByID(id, dataObject);
    this.$tableBody.append(newRow);
    return true;
}

它引用了jQuery和jQuery.tmpl(只是一种将数据转换为数据视图的方式,对于这个问题并不重要),我称之为:

var $j = jQuery.noConflict();
var peeps = [{ID:1, Name:'mary', Age:21},{ID:2,Name:'contrary', Age:12}];
var personIDGetter = function(person)
{
    return person.ID;
}
var theTableUpdater = updateableTable($j('table.updateable'), 'hi', peeps, personIDGetter);

但它告诉我(原型方法)addRow不存在。

我是不是错了?

更新 是的,我做了很多错事。我添加了jsfiddle with the suggested fixes以及其他一些修复程序。它会添加两行并删除一行。

0 个答案:

没有答案