JS: "this" undefined in named function parameters

Im trying to call a function to return one of my parameters as shown below:

functionCall({
    a: 'a',
    b: this._getB(),
});

the this value in this._getB() is undefined. If I remove this it seem's to work which is werid.

1 answer

  • answered 2018-02-13 03:25 ezakto

    this points to the current context, which is the current function scope by default (ie the function which is executing the code) or the the global object if you're not encapsulating the code.

    function currentFunction() { // <--- `this` points to this one
      functionCall({
          a: 'a',
          b: this._getB(),
      });
    }