Argo Argo - 3 months ago 8
Javascript Question

Object returns own property and preserves methods

I have on object that wraps some data:

function Obj1() {
var _foo = 'bar'
this.obj2 = {
'b': 'c'
}
this.method = function() {
return _foo
}
}
var obj1 = new Obj1()


Now when I call
console.log(obj1);
I want it to show me object
obj2
content. The trick is that I need to still be able to call
obj1.method
and get value of
_foo
. How do I do that if it's even possible?
My thought was that sth like getter will be suitable, but can't figure out where and how to assign one.

Answer

Sticking to your original snippet a factory looks like a good option:

function factory() {
    var foo = 'bar';
    var props = { b: 'c'};
    var proto = {
        method: function() { return 'foo' }
    }; 
    var obj = Object.create(proto);
    for (var prop in props) {
        if (props.hasOwnProperty(prop)) {
            obj[prop] = props[prop];
        }
    }
    return obj;
}

var obj = factory();
console.log(obj); // {b: 'c'}
console.log(obj.method()) // 'foo'

You could even pass props as an argument to get a more flexible way of spawning objects with an "unenumerable" method accessing private members.