Saturday, 15 August 2015

javascript - dynamically create prototypes and push to array -


I'm trying to dynamically create 'test' objects that are pushing into the array, I know That's the code given below, for reference to help solve my problem:

  var test = (function () {var blah; test.prototype .getNumber = function () {return blah;} test.prototype .setNumber = function (val) {blah = val;}}); Var array = (function () {var array []; array.prototype.get = function (index) {return array [index];} array.prototype.set = function (obj) {array.push (obj);} }); Var objArray = new array (); (Var i = 0; i & lt; 6; i ++) for (objArray.set ({setNumber (5);} = new test ());}  

The first step is to make the works of your constructor properly. It seems that you can use the local variables and closures In that case you have to assign methods for example, not prototype:

  this.setNumber = function () {return blah;}; // test.prototype //;   

for the array instead of setNumber = ...

< P> To add an example, just call a new test for example and its setNumber method:

 for  (Var i = 0; i & lt; 6; i ++) {var obj = new test (); obj.setNumber (5); objArray.set (obj);}  

Note: Constructor functions usually start with a capital letter.


No comments:

Post a Comment