javascript - How to push from forEach in prototype to array in constructor? -


this question has answer here:

if have global array this

var arr = [value1, value2...]; 

i got construcotor this

function myfunction() {     this.array = [];     this.toarray(); } 

and prototype method this

myfunction.prototype.toarray = function() {     arr.foreach(function() {         if (statement) {         // how can if here, want push current value, array in cunstructor function?         }     }); } 

as comment says, if comment is, want push current value in foreach function array in constructor function? tried this.array.push(); realized cant use since refers arr array.

edit if don't var = this in snippet above can :

myfunction.prototype.toarray = function(arr) {     arr.foreach((function(item) {         if (item%2 ===0) {            this.array.push(item);         }     }).bind(this)); } 

but prefer :

function myfunction() {      this.array = [];  }    myfunction.prototype.toarray = function(arr) {      arr.foreach((function(item) {          if (item%2 ===0) {             this.array.push(item);          }      }).bind(this));  }    var test = new myfunction();  var arr = [1, 2, 3, 4];  test.toarray(arr);  alert(test.array);


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -