0

Seeking clarification on the meaning of 'this' in this context. Why do I need to bind 'this' to the callback after the ajax request? When I check the debugger, it says 'this' is bound to the constructor whether I call bind or not.

var BugList = React.createClass({
getInitialState: function() {
    return {
        bugs: []
    }
},

componentDidMount: function() {

    $.ajax('/api/bugs').done(function(data) {
        this.setState({
            bugs: JSON.parse(data)
        });
    }.bind(this));
},
Norman Chan
  • 476
  • 4
  • 17
  • related: http://stackoverflow.com/questions/6889855/jquery-ajax-success-doesnt-work-with-this?noredirect=1&lq=1 – Kevin B Apr 06 '17 at 21:45
  • related: http://stackoverflow.com/a/33381852/2733506 – John Ruddell Apr 06 '17 at 21:46
  • *"When I check the debugger, it says 'this' is bound to the constructor whether I call bind or not.* -- What do you mean by this? There's no constructor in your example. Where do you check the binding of `this`? – Aaron Beall Apr 06 '17 at 23:15

1 Answers1

-1

That is because this by default this will point to the:

value of the ThisBinding of the current execution context;

Since your context will change during the time the callback actually runs, this will not refer to your current instance of BugList.

The .bind(this) essentially declares that no matter the context, set this to mean the context of where this function has been created (ie. BugList)

I'd recommend you look at: Standard ECMA-262, and Scopes in JS. For a more detailed explanation about this concept!

AP.
  • 8,082
  • 2
  • 24
  • 33