bind(this)意味着什么? [英] what does bind(this) means?
问题描述
我已经知道bind做了什么,它将你的给定对象或函数绑定到你想要的函数,但是 bind(this)
真的让我很困惑。什么是 中的
绑定的确意味着。
I already know that what bind do, it bound your given object or function to the function you want, but bind(this)
is really confusing me.What does this
in bind
really means.
以下是代码来自我的反应应用程序与firebase数据库。
Below is the code from my react app with firebase Database.
componentWillMount: function() {
this.firebaseRef = firebase.database().ref('todos');
this.firebaseRef.limitToLast(25).on('value', function(dataSnapshot) {
var items = [];
dataSnapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item['key'] = childSnapshot.key;
items.push(item);
}.bind(this));
this.setState({
todos: items
});
}.bind(this));
},
推荐答案
bind(this)
此处将 forEach()
中函数的上下文绑定到componentWillMount()的范围。
bind(this)
here binds the context of your function inside forEach()
to the scope of the componentWillMount().
这个
这里指的是 componentWillMount()$ c $的范围c>。
使用 bind(this)
,此
关键字将引用外部范围。
这是必不可少的,因为在这种情况下, forEach
函数中的 this.setState
可以作为其范围调用仅限于 componentWillMount()
。
With bind(this)
, this
keyword inside the inner function will refer to the outer scope.
This is essential because in this case this.setState
inside the forEach
function can be called as its scope is limited to componentWillMount()
.
根据 docs :
According to the docs:
bind()方法创建一个新函数当被调用时,将其
这个关键字设置为提供的值,并在调用新函数时提供任何前提的
参数序列。
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
查看此演示,演示 bind(this)的使用情况
。
class App extends React.Component {
constructor(){
super();
this.state = {
data: [{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}]
}
}
componentDidMount() {
this.state.data.forEach(function(item) {
console.log('outer scope ', this);
}.bind(this))
this.state.data.forEach(function(item) {
console.log('Inner scope ', this);
})
}
render() {
return (
<div>Hello</div>)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.js"></script>
<div id="app"></div>
这篇关于bind(this)意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!