Returning the copy of an object

Hello,

Please consider this bit of code:


function Foo() {
var obj = new SomeObj();
obj.setBlah("blah");
obj.doSomething();
obj.bar();

return obj;

}

Once obj is returned and used outisde the Foo() scope, will it be altered inside the Foo() scope? I’m not sure if I’m clear: I want obj to be “untouchable” within Foo(), I want to only allow modifications of the internal state of the object outside the Foo() scope.

The idea is that if obj is returned a second time, what has been done with the “first return” (so to speak) will not alter the way obj is returned the second time. In other words, I want to make sure that obj is always the same when Foo() returns it.

Is the code above ok, or should I prototype, or make a copy of obj and return that copy?

Hope I was clear enough…

:slight_smile:

With the above code it’s impossible to achieve what your trying to accomplish as with each call of Foo() your creating a new instance of SomeObj() which resets to the defaults no matter what, you would need to set the new instance of SomeObj() to a global var outside of Foo() and then check if the var is an instance of SomeObj(). E.g

var obj;

function foo() {
    if (!obj instanceof SomeObj) {
        obj = new SomeObj();
    }
    
    // Run code here...
    
    return obj;
}​

Yes, the code you posted seems to be doing what you are describing.
Unless SomeObj is changed itself Foo will always return a separate new object.