0
this.x = 9; 
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 81

this in module refer to the module itself.

// tutorial13.js
var CommentBox = React.createClass({
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList data={this.state.data} />
        <CommentForm />
      </div>
    );
  }
});

this in ajax function refer to the outter object which contains getInitialState function.

Why does not it refer to the inner ajax object which contains url property?

Jichao
  • 35,945
  • 40
  • 114
  • 183
  • 2
    An object literal has no special scope, nor this-value, it keeps the outer this-value, in this case from the function call. – adeneo Jul 10 '16 at 16:21
  • Alternative dupe: http://stackoverflow.com/questions/35809521/what-does-bind-do-on-an-ajax-call – Quentin Jul 10 '16 at 16:24

0 Answers0