Argo Argo - 1 month ago 5x
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
I want it to show me object
content. The trick is that I need to still be able to call
and get value of
. 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.


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.