0

Method:

a = {
  foo: 1,
  bar() {
    return this.foo + 1
  },
  lol: {
    baz() {
      return this.foo
    }
  }
}

a.bar() this which refers to a which is what I want. I'm looking for a way for the child method inside a.lol.baz to also have this refer to a. Is there anyway to do it?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Harry
  • 52,711
  • 71
  • 177
  • 261
  • 1
    Does this answer your question? [access parent object in javascript](https://stackoverflow.com/questions/1789892/access-parent-object-in-javascript) – lusc Mar 08 '22 at 20:12

2 Answers2

1

You can't refer to it directly. But you can bind the function to the object explicitly, then this will be available.

a = {
  foo: 1,
  bar() {
    return this.foo + 1
  },
  lol: {}
}

a.lol.baz = (function() {
  return this.foo
}).bind(a);

console.log(a.lol.baz());
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

you can use a.lol.baz.call(a) function

a = {
  foo: 1,
  bar() {
    return this.foo + 1
  },
  lol: {
    baz() {

      return this.foo
    }
  }
}
var res=a.lol.baz.call(a)
alert(res)
Suhail Keyjani
  • 488
  • 3
  • 10