-3

I am having tough time understanding the use of this keyword inside a class.

For example I have a class having a method like this (if this classifies as ES7 Syntax)

class something {

 methodA = () => {
 this.something = "Hey"
 }

 methodB = () => {
 this.something = "Yo"
 }
}

[Question] Will this be a valid syntax? Usually I have seen people creating constructor where they declare most of the stuff but then again that is ES6 hence they need to things like this.count = 0; inside a constructor for example...

class Clicker {
  constructor(element) {
    this.count = 0;
    this.elem = element;
    this.elem.addEventListener('click', this.click);

    // logs Clicker { count:0, elem: button#thing} as expected
    console.log(this);
  }

  click= () => {

    console.log(this);
    this.count++;
  } 

Answer to this question wasn't exactly much of a help to me "This" within es6 class method

If my above (class something) is wrong when using this keyword, can someone share any interesting articles about use of this keyword inside a class method in ES7

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210

1 Answers1

3

The syntax you're using in the first snippet are class fields, you can assign any value to this so this:

class Foo {
    value = 3;
}

is pretty much equivalent to

class Foo {
    constructor() {
        this.value = 3;
    }
}

This syntax is not yet official js but it's in the stage 3, meaning it's likely it will eventually be included in the language. https://github.com/tc39/proposal-class-fields

It's used in some codebases with the help of some transpiling tools that will convert bleeding-edge javascript to more supported javascript ( ES 5)

One interest of static property is that you can use it to replace method to have a better handling of this:

class Foo {
    someMethod = () => {
        console.log(this);
    };
}

is similar to

class Foo {
    constructor() {
        this.someMethod = () => console.log(this);
    }
}

which is similar to ( because of how arrow functions regarding to this) to:

class Foo {
    constructor() {
        const method = console.log(this);
        this.someMethod = method.bind(this);
    }
}

which means anytime you use the method, this will be bounded to that method and will refer to the instance instead of depending on how you called it.

More about the behavior of this in js: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Axnyff
  • 9,213
  • 4
  • 33
  • 37
  • Don't we use super when we are inheriting something from other class? if yes then why have we used super here? Also great answer Axnyff :) – Alwaysblue Jun 25 '18 at 21:05
  • 1
    You're absolutely right, I'm used to using it with React where we're always subclassing – Axnyff Jun 25 '18 at 21:07