Mohsin Mohsin - 11 days ago 4
Javascript Question

How to call prototype function within prototype function onclick event

How can I call prototype function within inside another prototype function

onclick
event in JavaScript?

function foo(){
this.table = '';
}

foo.prototype.abc = function(){
this.table = document.getElementById("tableID");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
this.xyz(this);
};
}
}
}

foo.prototype.xyz = function(tableCell){
alert(tableCell.innerHTML);
}


If I just call this
tableText
function instead of
this.xyz
it will work fine, but using
this.xyz
gives error in console
this.xyz(this)
is not a function

function tableText(tableCell) {
alert(tableCell.innerHTML);
}


My browser showing error but not JSFiddle
JS Fiddle

Answer

In this block of code:

table.rows[i].cells[j].onclick = function () {
    this.xyz(this);
};

this represents the td HTML object, not foo. You have to keep a reference of foo and pass it into onclick function, like this:

foo.prototype.abc = function(){
    var that = this; //Keep a reference of `foo`
    this.table = document.getElementById("tableID");
    if (table != null) {
        for (var i = 0; i < table.rows.length; i++) {
            for (var j = 0; j < table.rows[i].cells.length; j++)
            table.rows[i].cells[j].onclick = function () {
                //this.xyz(this);
                // "that" refer to the function foo
                // "this" refer to the current table cell (td)
                that.xyz(this);
            };
        }
    }
}
Comments