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