what does bind(this) means?

前端 未结 3 1107
别跟我提以往
别跟我提以往 2021-01-15 05:53

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

3条回答
  •  春和景丽
    2021-01-15 06:07

    You can play nice with this inside forEach - according to the https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach - instead of binding pass this as second argument for forEach statement.

    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 ( 
    Hello < /div>) } } ReactDOM.render( < App / > , document.getElementById('app'));
    
    
    

提交回复
热议问题