javascript - How to generate new instances of an object without the class? -


question:

how can generate new instances of class instance of class?

what i've found:

consider next class , instance:

// create 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 foo instance fo foo, , i'll using instance in examples.

object.create

with object.create can generate new copies of foo instance, share 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 logic in constructor not called.

prototype inheitance

this similar object create calls constructor. still has 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 example of want do, works in firefox:

// create bar class foo var bar = foo.constructor; bar.prototype = foo.__proto__; // firefox 

here have class bar that's copy of class foo , 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 other way achive same goal works in browsers?

1) proto has avoided obvious reasons, have object.getprototypeof read object's prototype in standard way.
2)you don't have constructor doing job, rather have kind of init method generate. make more sense have call this.generate @ end of constructor function. why prototype inheritance doesn't work : constructor not job. in same idea, cannot blame object.create since not neither constructor, nor generate in example, build object having same prototype, that's all.

provided add call this.generate constructor function, maybe easy way use constructor property of foo build new object :

var bar = new foo.constructor(); 

which give fresh new item.

so answer question : yes there's way, using constructor property of object instance build new item.

but no inheritance scheme able 'guess', full initialisation should performed such , such method. initialisation job of constructor. might imagine instance buil new array this.arr = []; in constructor , generate() push() items inside array, valid way. have avoid adding properties through method, both optimisation , clarity : setup instance properties within constructor, , maybe shared properties on prototype, , use properties in methods.


Comments