如何在foreach函数中获取父对象属性

how to get parent object property in foreach function

例如 我无法到达 'this.ret',所以在循环中使用 'obj.ret'。

这是正确的方法吗?

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()

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>

obj.sum()更改为obj.sum(arr)

您可以使用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>