2

It just occured to me that:

class Jamie {
    method function(){
        .... //Is a method
    }

    notAMethod = () => {
        ....//Is not a method?
    }
}

I am clearly confused in the matter, but why can't I use arrow functions and maintain the context of this = Jamie? Instead of using bind to keep context?

Jamie Hutber
  • 26,790
  • 46
  • 179
  • 291
  • No, that's a class property assigned to an arrow function. It itself is not a method. – Andrew Li Dec 03 '16 at 00:58
  • It's not part of ES6, as it's still a proposition , but you can use babel's [Class properties transform](https://babeljs.io/docs/plugins/transform-class-properties/) to do that. – Ori Drori Dec 03 '16 at 00:58
  • So indeed its not a method and just a property, this is bad practise imo. As it will cause unexpected behaviour. Yet so tempted for my being lazy. – Jamie Hutber Dec 03 '16 at 01:01
  • 1
    When you do `this.method = this.method.bind(this)` you get a property as well. Using arrow functions is shorter, and more expressive. – Ori Drori Dec 03 '16 at 01:03
  • `method function(){…}` is not exactly valid syntax. – Bergi Oct 12 '21 at 06:45

1 Answers1

0

You can use the constructor function and this keyword to assign those methods and have the right this working without any binds.

class Jamie {
    constructor () {
        this.getContext = () => {
            console.log(this) // returns Jamie
        }
    }
}
new Jamie().getContext()

In the example above, getContext will return Jamie class as it's this.

BaseScript
  • 381
  • 2
  • 7