0

I want to make a javascript object that can handle interaction with a headless CMS for me, but I am stuck at this simple problem. I cant figure out how to bind "this" the right way:

const car = {
  model: "Volvo",
  get: {
    getModel() {
      console.log("The car is: " + this.model);
    }
  }
}

car.get.getModel() // The car is undefined

When I simply log "this" inside getModel() I see that "this" refers to the get property. What am I doing wrong?

I have seen a solution where you use bind: const getModel = car.get.getModel.bind(car); but it seems like there should be a better way.

I created the object and tried using the method getModel(), but the way I structured it I can't get it to work.

ThS
  • 4,597
  • 2
  • 15
  • 27
  • Why do you have a nested object there? – Unmitigated Mar 16 '23 at 16:16
  • `this` is pretty notorious in javascript; it doesn't always mean what you might believe it to, or what it makes sense to mean – Derek Pollard Mar 16 '23 at 16:16
  • 1
    `this` is the object on which the method (`getModel`) was invoked. That object is `car.get` not `car`. (Why `car.get` exists the first place is a mystery, and probably a design error and creating it is what you did wrong). – Quentin Mar 16 '23 at 16:17
  • If you want to stick with that object structure, then after defining `car` just as you've done, try `const carObj = Object.create(car); carObj.get.getModel()` – Daniel Beck Mar 16 '23 at 16:20
  • Not sure if this stills works for you but for your case the object property is undefined because get is also a plain object so for your case this points to the object get. You can learn more about it here: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/this – Alfredo Esteban Hernndez Dvalo Mar 17 '23 at 03:36

0 Answers0