Home > Back-end >  how to get parent object property in foreach function
how to get parent object property in foreach function

Time:05-17

for example I can't reach 'this.ret' so use 'obj.ret' in loop.

is this right way?

const obj = {
  ret : 0,
  sum : function(arr){
     $.each(arr, function(i, v){
         obj.ret  = v //Can't reach this.ret
     })
     this.print();
  },
  print : function(){
    alert('sum is '   this.ret)
  }
}

    
let arr = [1,2,3,4,5]
obj.sum()

CodePudding user response:

You can use Arrow Function

const obj = {
  ret : 0,
  sum : function(arr){
     $.each(arr, (i, v) => {
         this.ret  = v
     })
     this.print();
  },
  print : function(){
    console.log('sum is '   this.ret)
  }
}

    
let arr = [1,2,3,4,5]
obj.sum(arr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

const obj = {
  ret : 0,
  sum : function(arr){
     $.each(arr, function(i, v){
         obj.ret  = v //Can't reach this.ret
     })
     this.print();
  },
  print : function(){
    console.log('sum is '   this.ret)
  }
}

    
let arr = [1,2,3,4,5]
obj.sum(arr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

change obj.sum() to obj.sum(arr)

  • Related