0

I am having tough time figuring out when should we preferably use this keyword and when shouldn't we use it..

For example, I was earlier doing something like this.

let socket; 
class something extends Component {

componentDidMount() {
 socket = openSocket('https://coincap.io');
}

componentDidUpdate() {
  socket.on('trades', (tradeMsg) => {
 }

componentWillUnmount() {
 this.socket.disconnect();
}

then someone re-structured my code did something like

 class something extends Component {

 componentDidMount() {
    this.socket = openSocket('https://coincap.io');
}

  componentDidUpdate() {
     this.socket.on('trades', (tradeMsg) => {
    }


componentWillUnmount() {
 this.socket.disconnect();
}

[Question:] While, Both the code works and do the job, I am perplexed between understanding which methods should we use and why did he used this keyword?

3
  • 2
    If you have two or more instances of something you will probably end up having a bad time with the first implementation Commented Sep 9, 2018 at 14:11
  • You need to ask yourself "Does this variable belong to an instance?". In your case, I believe you need one socket for each instance of something, then you should put socket as a property of the instance of something, otherwise, socket could be overridden later when a new something is initialized. Commented Sep 9, 2018 at 14:31
  • I saw you've updated code in repo - ANY reason to not placing displaySearchCrypto in state? Still two kinds of data managing in component? Commented Sep 10, 2018 at 9:02

2 Answers 2

3

You are dealing with ES6, which takes out a lot of ambiguity pertaining to the this keyword in the language.

Quite simply, this means (in the more traditional sense) the current scope; however, in JavaScript, this means the object calling the function as opposed to the current scope.

As mentioned previously, ES6 takes out a lot of complexity regarding variable hoisting and the likes.

Coming to your question, the reason it was refactored to this.something was because when your class is called (now, remember, JavaScript follows prototypal inheritance and is a first-class language; meaning that function prototypes are the class bases and functions can be passed as parameters) it will act like a function and the this keyword will refer to the object or the context where it was called.

If we have the following bit of code:

let foo = 'bar';
const fn = () => { console.log( this.foo ); }

fn();

The execution context would be window and the foo variable would be window.foo; hence, this.foo would translate to window.foo.

Similarly, your code will be transpiled something like:

var socket = new Socket();
function className() {}

className.prototype.someFunction = function() {

    console.log( socket );

}

Here, the this keyword would make sure that the current context is used instead of local variables which you might use within your function.

I hope this makes it clear. Here is a great article to understand the this keyword! :)

Sign up to request clarification or add additional context in comments.

2 Comments

,Thanks for such an amazing answer, What do you mean when you say prototypes are the class bases?
I mean that they form the classes since the ES6 class syntax is just sugar to make stuff more readable; in the end, it all boils down to that. Further, if you have to modify a class (add a function, say), you use the prototype 'myFunction prototype...'
1

The problem isn't the difference between this and a variable per se. It's that this refers to class instance and allows to have multiple class instances and thus multiple socket instances, while socket variable refers to specific socket instance and will be overridden in subsequent component instances.

The component will malfunction if there's more than one component instance at time, because socket variable refers to latest openSocket('https://coincap.io') result.

Also, this

let socket; 
class something extends Component {

componentDidMount() {
 socket = openSocket('https://coincap.io');
}

componentDidUpdate() {
  socket.on('trades', (tradeMsg) => {
 }

componentWillUnmount() {
 this.socket.disconnect();
}

will result in error on component unmount because there's no this.socket.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.