Question:
How can I generate new instances of a class from an instance of that class?
What I've found:
Consider the next class and its instance:
// Create a new class
var Foo = function Foo () {
console.log('New instance of FOO!');
};
Foo.prototype.generate = function(first_argument) {
this.arr = [1,2,3,4,5];
};
var foo = new Foo();
foo.generate();
console.log(foo.arr); // [1,2,3,4,5]
Note that foo
is as an instance fo Foo
, and i'll be using this instance in the examples.
Object.create
With Object.create I can generate new copies of the foo instance, but they will share the state data:
var bar = Object.create(foo);
console.log(bar.arr); // [1,2,3,4,5]
bar.arr.push(6);
console.log(foo.arr); // [1,2,3,4,5,6]
console.log(bar.arr); // [1,2,3,4,5,6]
And if some logic is in the constructor it is not called.
Prototype inheitance
This is similar to the object create but it calls the constructor. It still has the same state data problem:
var Bar = function () {
foo.constructor.call(this);
};
Bar.prototype = foo;
var bar = new Bar();
console.log(bar.arr); // [1,2,3,4,5]
bar.arr.push(6);
console.log(foo.arr); // [1,2,3,4,5,6]
console.log(bar.arr); // [1,2,3,4,5,6]
Firefox proto
Here is an example of what I exactly want to do, but it only works in Firefox:
// Create Bar class from foo
var Bar = foo.constructor;
Bar.prototype = foo.__proto__; // Firefox only
Here I have the class Bar that's a copy of the class Foo and I can generate new instances.
var bar = new Bar();
console.log(bar.arr); // undefined
bar.generate();
console.log(bar.arr); // [1,2,3,4,5]
Is there any other way to achive the same goal that works in all the browsers?