Doing a search to see where we are currently with classes and private methods and came across this sitepoint article https://www.sitepoint.com/javascript-private-class-fields/
It appears you can now define methods with arrow functions bound to this, which came as a bit of a surprise.
One difference is arrow methods are defined as if inside of a constructor and are created on the instance rather than the prototype
Just some tests
Arrow method
class Test1 {
a = 10
// created on the instance
loggit = () => {
console.log(this.a)
}
}
const test1 = new Test1()
test1.loggit() // expect undefined get 10
console.dir(test1)
/*
Test1
a: 10
loggit: () => { console.log(this.a) }
__proto__: Object
*/
Prototype method
class Test2 {
a = 30
// created on the prototype
loggit() {
console.log(this.a)
}
}
const test2 = new Test2()
test2.loggit() // expect 30 get 30
console.dir(test2)
/*
Test2
a: 30
__proto__:
constructor: class Test2
loggit: ƒ loggit()
__proto__: Object
*/
Object Literal
Arrow function will still fail here
const testLiteral = {
a : 20,
loggit: () => {
console.log(this.a) // this is found on window
}
}
testLiteral.loggit() // expect undefined get undefined
Just thought I would share.