0

I'm writing some client-side Javascript, where I want to render some tabs and a table. This is the relevant code:

(function() {

    var Table = function() {
        this.render = function() {
            console.log('rendering table');
        };
        return this;
    };

    var Tabs = function() {
        var table = Table();
        this.render = function() {
            console.log('rendering tabs');
            table.render();
        };
        return this;
    };

    (function() {
        var tabs = Tabs();
        tabs.render();
    })();

})();

What I expect: the console should show rendering tabs, rendering table, and be done with it.

What actually happens: the console shows thousands of rendering tabs until jsFiddle crashes.

This shows that table.render() actually calls tabs.render() recursively. But why? I found this behaviour quite puzzling, can somebody explain where my mistake is?

1
  • 1
    Use new Tabs() and new Table()
    – CD..
    May 1, 2015 at 12:04

1 Answer 1

1

Your mistake is the way you are calling Tabs:

var tabs = new Tabs();
tabs.render();

And Table:

var table = new Table();

The reason for your issue is that this refers to the global object (window) when the function is not invoked with the new operator. The first thing Tabs does is call Table, and both set this.render. When invoked with new each will have its own context and therefore its own render method.

1
  • Perfect, thanks! I now also added "use strict"; to the top of my file to be warned of such problems.
    – modemuser
    May 1, 2015 at 12:16

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.