Results 1 to 5 of 5

Thread: Cloning Objects

  1. #1
    Join Date
    May 2007
    Location
    USA
    Posts
    373
    Thanks
    2
    Thanked 4 Times in 4 Posts

    Default Cloning Objects

    What would be the best way to clone an object? (I don't want to create a new reference to an object.)

    The reason I want to do this is to clone Event objects so I can later reference them instead of the current one using timeouts.

    I was thinking around the lines of this:
    Code:
    function clone(o) {
    	var clone = {};
    	for(var i in o) {
    		clone[i] = o[i];
    		}
    	return clone;
    	}
    Last edited by Trinithis; 06-09-2007 at 11:02 PM.

  2. #2
    Join Date
    May 2007
    Location
    USA
    Posts
    373
    Thanks
    2
    Thanked 4 Times in 4 Posts

    Default

    Hmm, but that doesn't work.

    Edit: Oh, I need to take out the quotes. Will fix.

  3. #3
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    I've a function to do just this in this library.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  4. #4
    Join Date
    May 2007
    Location
    USA
    Posts
    373
    Thanks
    2
    Thanked 4 Times in 4 Posts

    Default

    Thanks. So it should look something like:
    Code:
    function clone(o, deep) {
    	var clone = o instanceof Array ? [] : {};
    	for(var x in o) {
    		if(deep && typeof o[x]==="object") clone[x] = copy(o[x], true);
    		else clone[x] = o[x];
    		}
    	return clone;
    	}

  5. #5
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Yep, that looks about right.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

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
  •