J
J
jww2017-09-17 21:59:42
JavaScript
jww, 2017-09-17 21:59:42

How to bind a function to an object context if the function is declared and called in the context of another function?

Hello. I'm trying to understand the subtleties of OOP. Now the main misunderstanding is how to bind the rangeEnd function to an object. I did it through arrow functions, everything was fine with them, because they do not have their this, I understood this, but why can't I bind rangeEnd to an object? I think my mistake is that I bind it to the handlerClick context, but how do I bind it to an object? The most important condition is that the function must be declared and called inside the handlerClick function.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isOpened: false
    };
  };
  handlerClick(event) {
    function rangeEnd(thisPage) {
      let end = thisPage + 2;
      return (end <= totalPages) ? end : thisPage;
    }
    this.rangeEnd.bind(this, 5)
  }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
Javid Askerov, 2017-09-17
@jww

What does handlerClick return? In any case, I understand that it should be like this:

// в конструкторе
    this.handlerClick = this.handlerClick.bind(this);
// в функции handlerClick 
rangeEnd.bind(this, 5);

H
holymotion, 2017-09-17
@holymotion

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isOpened: false
    };
  };
  handlerClick(event) {
    function rangeEnd(thisPage) {
      let end = thisPage + 2;
      return (end <= totalPages) ? end : thisPage;
    }
    rangeEnd.bind(this); 
  }
}

V
Vladimir, 2017-09-18
@Casufi

You bind, but do not call, but in general the task is wild, to create a function inside the method of the instance, inside to refer to the properties of the instance, isn't it easier to make this function another method of this instance?
https://jsfiddle.net/44rg8hjk/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question