2

I'm actually new to programming and this community. Currently I'm working on a code that facing a scope issue with object literals. can anyone help me with this?

var obj = {
   value: 3,
   print:()=>console.log(value)
}

obj.print();

When we are using non arrow functions it is working. I can only use arrow functions here.

7
  • Can you include errors? Commented Dec 12, 2022 at 15:56
  • Even a regular function would not work here Commented Dec 12, 2022 at 15:58
  • you need this.value for non-arrow function Commented Dec 12, 2022 at 15:59
  • @Marios that won't work because the code uses a => function Commented Dec 12, 2022 at 16:00
  • 1
    @Pointy yeah I meant the regular function as he said, I should have made it clear Commented Dec 12, 2022 at 16:00

2 Answers 2

3

You can either use the this keyword to reference the object, but then you would have use a regular function instead of an arrow function.

const obj = {
  value: 3,
  print() {
    console.log(this.value)
  },
};

obj.print();

Or you can reference the object directly (better to use previous approach).

const obj = {
  value: 3,
  print: () => console.log(obj.value),
};

obj.print();

Sign up to request clarification or add additional context in comments.

Comments

1

The only solution that comes to my mind is to use the reference if you only want to use the arrow functions.

var obj = {
   value: 3,
   print:()=>console.log(obj.value)
}

obj.print(); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.