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 !
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 !
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.
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
.
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! :)
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
Another way to do this, using JQuery is the function Jquery.extend. You can use it like this:
var b = jQuery.extend({},a);