-1

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?

2

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thanks! I now also added "use strict"; to the top of my file to be warned of such problems.

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.