@
@
@Richswitch2018-03-20 19:57:46
JavaScript
@Richswitch, 2018-03-20 19:57:46

How to understand when this is needed in OOP, and when not?

Hey!
I'm using eslint, which gives me a class methods use this error when I write a method without anything that has a this context . And then I got a question. Why do I need this if I can get around, in a certain section of code, without this , using only const let .
I also use the open source code for the calendar. In which the variables are set like this:

findBlocks: function() {
        this.popup = $('.datepicker__calendar');
        this.prev = $('.calendar__button_type_prev');
        this.next = $('.calendar__button_type_next');
        this.header = $('.calendar__button_type_current');
        this.fieldInput = $('.datepicker__input');

        this.content = $('.calendar__content');
        this.yearsWrap = $('.calendar__years');
        this.datesWrap = $('.calendar__dates');
        this.monthsWrap = $('.calendar__months');

        this.today = $('.calendar__today');

        return this;
      },

true, the type used the old standard, but it doesn't matter, I can easily set var variables within this method.
But now explain to me when to use this context?
How to declare variables in methods: Like
this?
const users = document.querySelectorAll('.event-users__filter-users');

Or so?
this.users = document.querySelectorAll('.event-users__filter-users');

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vith77, 2018-03-20
_

It's essentially a constructor function. If you call it with new, these variables will become properties of the created object. this is not used to create variables, this is a context that depends on how the function was called. There are 4 ways in total) Call simply as a function 2) Call with new 3) Call as a function of an object 4) Call with call, apply.
Using var, const, let is about something else - it's about creating variables in some scope (global, inside a function or block)
In the example with const users = created a variable, in the example with this.users = created a property on the object on which specifies this.

V
Vitaly, 2018-03-20
@vitstr

If you use class sugar from es2015 - use the second method.
UPD: I was in a hurry .. As I understand it, you already use classes.
If you are only using a variable in a method, use let/const. And in the event that you need data in a class instance, then define properties and use them through this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question