0

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

1 Answer 1

1

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);
            };
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.