Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
how to get parent object property in foreach function

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()
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!