Dev Notes

Software Development Resources by David Egan.

JavaScript Functions


JavaScript
David Egan

Method Invocation Pattern

Function defined as an object property - an object method:

const myObject = {
  value: 0,
  increment: function(val) {
    this.value += typeof val === 'number' ? val : 1
  }
}

JavaScript binds this at execution (late binding), so this refers to the myObject object.

Function Invocation Pattern

Function invocation uses the format functionName(). In this case, this within the function refers to the global object. This can be incredibly confusing. The problem is evident when using an inner function within a method:

const myObject = {
  value: 1,
  double: function() {
    // In the inner function, `this` refers to the global object (e.g. `Window`).
    // Intuitively, you'd expect it to refer to the containing object - it does not.
    // A workaround is to assign a variable to `this` in the outer function.
    // By convention, this variable is named `that`.
    let that = this
    let helper = function() {
      that.value = that.value * 2
    }
    helper()
  }
}

ES6 arrow functions provide a much less hacky solution, since the arrow function this is inherited from the containing scope. The above example, rewritten with an arrow function:

const myObject = {
  value: 1,
  double: function() {
    let helper = () => {
      this.value = this.value * 2
    }
    helper()
  }
}

comments powered by Disqus