Javascript This and Double Arrow Functions

August 21, 2018

Object method

util = {
  message: 'hello',
  test1() {
    // return hello
    return this.message
  },
  test2: function() {
    return this.message
  },
  test3: () => {
    // this = window
    return this.message
  }
}

console.log(util.test1()) // hello
console.log(util.test2()) // hello
console.log(util.test3()) // undefined - this = global window

Use normal function for object method.

Callback

util = {
  message: 'hello',
  test4() {
    const test = () => {
      return this.message
    }
    return test()
  },
  test5() {
    const test = function() {
      return self.message
    }
    return test()
  },
  test6() {
    const self = this
    const test = function() {
      return self.message
    }
    return test()
  }   
}

console.log(util.test4()) // hello
console.log(util.test5()) // undefined - this = global window
console.log(util.test6()) // hello

Use doule arrow function for callback.

References

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.