这是什么意思?

what does bind(this) means?

本文关键字:意思 是什么      更新时间:2023-09-26

我已经知道bind做什么了,它把你给定的对象或函数绑定到你想要的函数,但是bind(this)真的让我很困惑。bind中的this到底是什么意思

下面是我的react应用与firebase数据库的代码。

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()的作用域。

这里的this指的是componentWillMount()的作用域。

对于bind(this),内部函数中的this关键字将指向外部作用域。这是必要的,因为在这种情况下,forEach函数中的this.setState可以被调用,因为它的作用域被限制为componentWillMount()

根据docs:

bind()方法创建了一个新函数,当调用该函数时,该函数具有其此关键字设置为所提供的值,具有给定的序列在调用新函数时提供的任何前面的参数。

查看这个演示,它说明了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>

您没有显示完整的React组件定义,但它很可能指的是您的componentWillMount定义的React组件实例

您可以在forEach中使用this -根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach -而不是将this绑定为forEach语句的第二个参数。

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);
      }, this) // be nice for context - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
    }
    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>