1

I have

var a = {
    f1: function() {
        // Do Something
    },
    f2: ['a','b','c'],
    f3: 1234
}

I need to create something like this

var b = Object.create(a);

But b is not showing me that it contains any of the properties of a !

Storm
  • 4,307
  • 11
  • 40
  • 57
  • `b` has `a` as it's prototype, so as long as you don't overwrite the same property on `b`, they will be looked up on `a` upon access. – Yoshi Feb 21 '13 at 11:51
  • exact duplicate of [Copying an Object in Javascript](http://stackoverflow.com/questions/728360/copying-an-object-in-javascript) – Bergi Feb 21 '13 at 11:57
  • I'm sorry because I wrote my answer but I had a little mistake. Check it out because now I've fixed it and also wrote a better description. Notice that this is just JavaScript code, which is the best to learn the advanced aspects of the language, but you can use jQuery's extend method too ok? :) – albertoblaz Feb 21 '13 at 21:51

3 Answers3

2

You can create a clone function, doing something like this:

var clone = function(obj) {

    // Create a new object using the same prototype as the original object
    var cloned = Object.create(obj);      

    // Copy each property from 'obj' to 'cloned'
    for (p in obj) {      
        if (obj.hasOwnProperty(p)) {
            cloned[p] = obj[p];
        }
    }

    return cloned;        // Return the cloned object
}

EDIT: Be careful with the first statement to create the cloned object from the original.

  1. You have to notice that if you write var cloned = {}; as I did before, the prototypes would be different, so this solution will not work properly at 100% because if you use the instanceof operator, it will return false.

  2. If you use just var cloned = Object.create(obj); as other answers describe, you just will obtain a cloned object with a similar prototype than the original's prototype. But you also need to copy the properties from the original object and attach them to the cloned version. That's the reason we have to use the for-loop.

Finally, if the second previous approach using Object.create does not work in your browser because it has a legacy JavaScript engine, then you have to use a small workaround as the following.

function F() {};
F.prototype = obj.prototype;
var cloned = new F();

Hope it helps! :)

albertoblaz
  • 590
  • 5
  • 19
0

Use prototype:

var b = Object.create(a.prototype);

Object.create Creates a new object with the specified prototype object and properties.

It expects the prototype for the newly created object: Object.create(proto [, propertiesObject ])

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create

Darren
  • 68,902
  • 24
  • 138
  • 144
0

Another way to do this, using JQuery is the function Jquery.extend. You can use it like this:

var b = jQuery.extend({},a);