0

Lets say I have this code, with normal function:

let a = {
  parent: "roger",
  child: "bear",

  printName: function() {
    console.log(`${this.parent} ${this.child}`)
  }
}

b = {
  parent: "float",
  child: "bear",
}

a.printName.call(b)

The output is as expected:

float bear

However, the same code with anonymous function doesn't work:

let a = {
  parent: "roger",
  child: "bear",

  printName: () => {
    console.log(`${this.parent} ${this.child}`)
  }
}

b = {
  parent: "float",
  child: "bear",
}

a.printName.call(b)

This results in:

undefined undefined

Even passing 'this' to anonymous doesn't seem to work:

let a = {
    parent: "roger",
    child: "bear",

    printName: (this) => {
        console.log(`${this.parent} ${this.child}`)
    }
}

This results in a syntax error: Unexpected token this

Questions:

  • Please explain why is this happening?
  • How to get it to work?
h-sifat
  • 1,455
  • 3
  • 19
  • 2
    It's already working. Use the first version. – deceze Feb 09 '22 at 15:45
  • 1
    "*How to get it to work?*" you ***cannot*** unless you change your code a lot. Yet, there doesn't seem to be a reason to really do that. Further reading: [What does "this" refer to in arrow functions in ES6?](https://stackoverflow.com/q/28371982) | [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/q/31095710) | [What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?](https://stackoverflow.com/q/24900875) | [Self-references in object literals / initializers](https://stackoverflow.com/q/4616202) – VLAZ Feb 09 '22 at 15:48
  • 2
    As clarification -> `function() {}` is an anonymous function, and `() => {}` is an arrow function. Could explain why you couldn't find the answer.. :_ – Keith Feb 09 '22 at 15:53

0 Answers0