If you use a function of type methodical below, it will create a method in which this is passed as the first argument to the callback. Thus, you have all the advantages of the thick arrow syntax (implicit return, this not lost on subsequent function calls), but can still use it as a method. Of course, there is also a short method syntax that basically creates the traditional es5 style function (slightly different since it cannot be called with the new one).
const methodical = func => function(...args) { return func(this, ...args) } const add = methodical( (instance, name, value) => (instance[name] = value, instance) ) const a = { add } a.add('first', 1.23).add('second', 2.74) add.call(a,'third', 3.11) console.log(JSON.stringify(a, null, 2))
using es2015 shorthand methods instead
const b = { add(name,value) { this[name] = value return this } } b.add('first',1).add('second',2) console.log(JSON.stringify(b))
source share