RangeError: Maximum call stack size exceeded when debugging/logging/inspecting an Object in Node.js

Given a class definition as below, I am getting RangeError: Maximum call stack size exceeded when trying to see which properties the Object has.

var Person = (function () {
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    Person.prototype.inspect = function () {
        console.log(this);
    };
    return Person;
})();

var radek = new Person("Radek", 28);
radek.inspect();

In browser (Chrome), we will get the following though:

Person {name: "Radek", age: 28, inspect: function}

Funny you should ask. By default custom inspect() functions defined on the objects being inspected will be called when we try to inspect them. This leads into a recursion with no end in our case.

To alleviate the problem while preserving the name use the util module passing an extra option customInspect into inspect():

var util = require("util");

var Person = (function () {
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    Person.prototype.inspect = function () {
        console.log(util.inspect(this, { 'customInspect': false }));
    };
    return Person;
})();

var radek = new Person("Radek", 28);
radek.inspect();

Which will give us the following:

{ name: 'Radek', age: 28 }