关于Javascript中的this关键字

今天在学习react的官方教程时,看到了这样一段jquery的ajax代码
地址:http://reactjs.cn/react/docs/tutorial.html

// 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>
 );
 }
});

其中指定的success的调用函数为
function(data) {
this.setState({data: data});
}.bind(this)
对这里bind的使用颇为不解,遂查阅资料
这是msdn上bind方法的页面
https://msdn.microsoft.com/zh-cn/library/ff841995

其中讨论到了this关键字,于是又百度了一些内容,其中几篇有较大帮助如下:
apply、call、bind:http://www.admin10000.com/document/6711.html
javascript中的上下文:http://blogread.cn/it/article/6178
this的工作原理:http://blog.jobbole.com/67347/

理解this关键字的核心在于,理解javascript中一切皆为对象的理念。
一旦进入了一个函数,那么上下文就会发生改变,随之this指向也会发生改变。
通过apply,call,bind函数,可以改变函数中this。

回头来看代码,其中
success: function(data) {
this.setState({data: data});
}.bind(this)

bind函数的作用是返回一个新函数,这个函数中的this保证了指向bind的参数。success的内容即为这个新函数。

而bind(this)中的this,其所在的上下文则是componentDidMount这一方法(大概)。而当函数作为对象方法使用时,其this指向的是这个对象。
因此,这个ajax的作用,是在调用成功后,执行对象的setState方法。

显然,不使用bind(this)的话,this.setState中的this会是undefined

你可能感兴趣的:(关于Javascript中的this关键字)