0

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

prem_kumar
  • 59
  • 6
  • 1
    the anonymous function passes `this` within the scope of `test()`. You need to use a named function. See: [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) or [Understanding “this” within anonymous function in JavaScript](https://stackoverflow.com/questions/31651685/understanding-this-within-anonymous-function-in-javascript) – pilchard Dec 03 '20 at 13:05
  • See also [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/q/31095710/215552) – Heretic Monkey Dec 03 '20 at 13:09
  • Does this answer your question? [Understanding "this" within anonymous function in JavaScript](https://stackoverflow.com/questions/31651685/understanding-this-within-anonymous-function-in-javascript) – pilchard Dec 03 '20 at 13:09

2 Answers2

4

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();
Liam
  • 22,818
  • 25
  • 93
  • 157
  • Can you please explain me what is the difference between the both function. I am assigning a function to a fn key but you are defining a function in a object. At the end the function fn going to be called why it behaves different – prem_kumar Dec 03 '20 at 13:05
  • 1
    arrow functions do not have their own "this" as regular functions – Jose Miguel Salazar Dec 03 '20 at 13:07
1

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