为什么我们要在 AJAX
的 success 回调函数上调用 bind
方法?
看一下这段代码:
$.ajax({
url: myurl,
dataType: 'json',
success: function(data){
this.setState({data: data});
}.bind(this)
});
如果我们不调用
bind
,那么使用bind
会有什么区别或优势吗?为什么我们要在 AJAX
的 success 回调函数上调用 bind
方法?
看一下这段代码:
$.ajax({
url: myurl,
dataType: 'json',
success: function(data){
this.setState({data: data});
}.bind(this)
});
bind
,那么使用bind
会有什么区别或优势吗?在IT技术中,为了确保回调函数的上下文(this
)正确无误,您需要调用bind()
方法。否则,默认情况下会在全局上下文中调用它(显然,jQuery使用jqXHR对象作为上下文来调用它)。bind()
将函数的上下文设置为this
所代表的值。
@shubham,这是JavaScript中使用当前this关键字在回调函数中的语法,就像你在以下提到的:
success: function(data){
this.setState({data: data});
}
bind()
函数的第一个参数将作为调用函数中的this,你应该去了解apply()
和call()
函数,因为这对你会有帮助。
bind
是一个转换函数。代码如下:componentDidMount: function() {
var _this = this;
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
_this.setState({data: data});
}
});
},
等同于:
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this)
});
},
到目前为止,我认为你已经理解了bind函数是什么以及为什么要使用bind
来实现它。