Javascript“this”-引用包含对象

Javascript `this` - reference containing object

本文关键字:引用 包含 对象 this Javascript      更新时间:2023-09-26

我正在使用Javascript和React构建前端。我不知道如何引用包含对象的方法:

     var RAttribute = React.createClass({
        loadAssignmentsForList: function(elem) {
                //other code
            },
            render: function() {
                    var assignmentsLoading = this.props.assignmentsLoading;
                    var lists = this.props.data.lists.map(function(elem) {
                       return (<li className='list-group-item grey'>
                         <div className='list-group'>
                           <RList key = {elem.name} data={elem}
                              assignmentsLoading={assignmentsLoading}
                              loadAssignmentsForList={this.loadAssignmentsForList(elem)}/>
                       </div>
                      </li>);
                    });
                    //other code
          }
       //other code
     });

我正在尝试从render内调用loadAssignmentsForList,因此我正在使用this.loadAssignmentsForList(elem)。然而,我得到了以下错误。

Uncaught TypeError: Cannot read property 'loadAssignmentsForList' of undefined

.this绑定到.map.map中的this不引用RAttribute对象

var lists = this.props.data.lists.map(function(elem) {
   // your code             
}.bind(this));

或者您可以通过第二个参数将this设置为.map,比如这个

var lists = this.props.data.lists.map(function(elem) {
   // your code             
}, this);

此外,如果您使用ES6,您可以使用箭头功能

var lists = this.props.data.lists.map((elem) => {
   // your code             
});
相关文章: