1

I have implemented this immutable Pos object:

var Pos = function(x, y) {
    var _x = x;
    var _y = y;
    return {
        x: function() { return _x; },
        y: function() { return _y; },
    };
}

Now when I write new Pos(5, 7) to the console, it is displayed like this:

▶ Object {x: function, y: function} // Chrome
Object { x: Pos/<.x(), y: Pos/<.y() } // Firefox

That is not useful at all, as I cannot see the values for x and y. I could make a custom function to log x and y, but that would really not be as good, and I would lose the useful possibility to expand the object and navigate inside (imagine more complex objects, Pos is just one example).

If it was in C#, I would just override ToString(), and then Visual Studio would automatically use it in the debugger to display my object.

In JS however implementing toString doesn't seem to help at all. Is there any way to see my object's x and y easily in the console?

4
  • chrome is already showing you the x and y values, which are functions. use getters if you want getters; for example: get x() { return _x; }, otherwise, there's no link to the private var w/o executing the method, which the console won't do for obvious reasons. Commented Jul 5, 2016 at 20:14
  • @dandavis Interesting, I didn't know there were getters in JS. Let me check if this works. Commented Jul 5, 2016 at 20:22
  • yeah, a lot of coders overlook them, but they were added in ES5 and now work everywhere (ie8+). Commented Jul 5, 2016 at 20:24
  • I'm not sure how to make getters work with my kind of object (I'm a JS newbie). Could you please post some sample code as an answer? Commented Jul 5, 2016 at 20:29

1 Answer 1

2

You can get better console behavior in chrome, maybe others, using ES5 getters:

function Pos(x, y) {
    return {
        get x() { return x; },
        get y() { return y; },
    };
}
console.log( Pos(1,5) );

to avoid possible wasted cpu, chrome won't calc the getter in the console until you click on it, but at least that's all you have to do. Above and beyond that, you'll have to craft your own logger method, or use completely custom objects.

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

1 Comment

Ok, getters seem to work in the console, I get ▶ Object {x: (...), y: (...)}, and then clicking the (...) expands it to show the value. That's not as good as in C#, especially if I have lots of values to view, but it is better than nothing. Thank you.

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.