bind(this)意味着什么?

时间:2016-11-03 07:10:15

标签: javascript reactjs

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

以下是我的反应应用程序与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));

  },

3 个答案:

答案 0 :(得分:2)

bind(this)这里将forEach()内函数的上下文绑定到componentWillMount()的范围。

this这里指的是componentWillMount()

的范围

使用bind(this),内部函数内的this关键字将引用外部范围。 这很重要,因为在这种情况下this.setState函数内的forEach可以被调用,因为它的范围仅限于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'));
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

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

答案 2 :(得分:0)

根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach,您可以与this内的forEach进行良好匹配 - 而不是将this绑定为forEach语句的第二个参数。< / p>

&#13;
&#13;
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'));
&#13;
<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>
&#13;
&#13;
&#13;

相关问题