How to access the property from method defined in the same object javascript

74 Views Asked by At

I have defined a function which returns object which has property and a method. using the returned object I am calling the method inside the object to get the value of the property in the object. but I didn't received what I expected.

function test(){

    return {
        a:'test property',
        fn:()=>{
             console.log('property', this.a);
        }
    }

}

 const obj = test();
 obj.fn() // what I expect is test property but I received undefined.

enter image description here

2

There are 2 best solutions below

0
On

When you use a regular function this is scoped to how it is called. example

obj.fn()

obj is taken as your this

when you define using arrow function this is assigned on creation which points to the parent's context in your case its window

2
On

You have declared the function incorrectly. Remember that arrow functions do not have their own this like a regular function does.

You should declare it like this:

function test() {
  return {
    a: 'test property',
    fn() {
      console.log('property', this.a);
    },
  };
}
const obj = test();
obj.fn();