我正在从 https://facebook.github.io/react/docs/tutorial.html 学习 ReactJS
还有一个从服务器下载 JSON 数据的示例,我不太明白。 我有这个方法:
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
但是为什么会有.bind(this)
它的目的是什么?我尝试在 jQuery 文档( http://api.jquery.com/bind/ )中查找它,但不知何故,我发现文档中所示的使用它与我在 React 中的使用方式之间没有任何联系。
最佳答案
由于 JavaScript 上的变量作用域。因为你在一个函数内部,就像这样:
success: function(data) {
this.setState({data: data});
}
您的“this
”将引用 success 函数内的范围。当你在函数后面执行 .bind(this)
时,它告诉 JS 你想使用 this 的外部引用。在您的情况下,外部函数“loadCommentsFromServer
”的作用域
此外,我建议您进一步阅读: http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/
http://www.smashingmagazine.com/2014/01/23/understanding-javascript-function-prototype-bind/
关于javascript - ReactJS - 使用 jQuery 从服务器加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29877707/