SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Returning the copy of an object

    Hello,

    Please consider this bit of code:

    Code JavaScript:
    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...


  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,197
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    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

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

  3. #3
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,117
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    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.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •