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

163
Views
Arrow Function returns undefined when called from an object but returns a string when called from a class instance

1. I am calling a function myDes() which is an Arrow Function inside an Object Cameras. It is returning undefined.

2. But when I call the function myDes() from a Class instance obj1 it returns a string - "abc".

In my understanding arrow function binds by default the properties of the parent function or the global scope, then why does it not return the price in the first example as it does name in the second?

Example 1 — Calling from an Object

const cameras = {
  price: 600,
  weight: 2000,
  myDes: () => {
    return `This canon camera is of ${this.price}`
  }
}

console.log(cameras.myDes()) // price undefined

Example 2 — Calling from an Instance of a Class

class Student {
  name = 'abc'
  myDes = () => {
    console.log(this.name)
  }
}

let obj = new Student
obj.myDes() // return abc

*

To the Comments Below suggesting some link reference for answers. What I meant since there is no parent function around the arrow function in the Class then how the arrow function is inheriting the properties of the class. To which a satisfied answer has been provided

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

In your first example, there is no parent function around the arrow function definition, so it does indeed bind to the global this. An arrow function is not a method of the object.

In your second example, you are using class field syntax. This is actually syntactic sugar for

class Student {
  constructor() {
    this.name = 'abc'
    this.myDes = () => {
      console.log(this.name)
    }
  }
}

where the parent function is the constructor of the class, whose this value refers to the instance. This is also the value that the this inside the arrow function will refer to.

about 4 years ago · Juan Pablo Isaza Report

0

As the comments to your question state, this inside arrow functions do not behave like you think. You may do this instead:

const cameras = {
  price:600,
  weight: 2000,
  myDes: function(){
    return `This canon camera is of ${this.price}`
  }
}

console.log(cameras.myDes())

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!