Javascript This and Double Arrow Functions

Aug 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()) // helloconsole.log(util.test2()) // helloconsole.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()) // helloconsole.log(util.test5()) // undefined - this = global windowconsole.log(util.test6()) // hello

Use doule arrow function for callback.

References

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.