Home > OS >  Scope issue within JavaScript Object literal
Scope issue within JavaScript Object literal

Time:12-13

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.

CodePudding user response:

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

CodePudding user response:

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(); 
  • Related