Home > front end >  javascript using this in a child method
javascript using this in a child method

Time:03-09

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?

CodePudding user response:

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());

CodePudding user response:

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)

  • Related