将“this”传递给类 ECMASCRIPT 6 中的回调

pass 'this' to callback in a class ecmascript 6

本文关键字:ECMASCRIPT 回调 this      更新时间:2023-09-26

我在 ecmascript 6 中有一个类。我需要将值"this"传递给回调。

我尝试使用.bind(this)。到目前为止似乎不起作用。我还尝试设置 var _this = this; 并在回调中使用_this。它仍然不起作用

     class Modal {
        constructor(modal) {
        this._modal = modal;
        this.id = this._options.id;      
       }
    }
    open(opts) {
        let modalOptions = {
            size: opts.size || '',
                templateUrl: 'modal.html',
                controller: function controller($scope, $uibModalInstance) {
                    var _this = this; 
                    this._options = {
                        id: opts.id
                    };
                    this.hcbuttons: [{id: '1', name: 'test'}, {id: '2', name: 'abc'}];
                    publisher.subscribe('triggered', this._options.id, function(event, creator) {
                        //as soon as we subscribe to the published event
                        var result = this.hcbuttons.filter(function( obj ) {
                            return obj.id == creator;
                        })[0];
                        if(result.sync === true) {
                            console.log('disabledall');
                        }                         
                    }).bind(this);

        }
} 

您错误地绑定了this。您正在通过函数的返回值调用绑定subscribe。函数对象在其原型中仅具有函数bind。因此,将您的代码从此}).bind(this);}.bind(this))

由于要this设置为模态类,

 //change one
 open(opts) {
        var _this = this;
        let modalOptions = {
 //~~~~~~~~~~~~~~~~~~~~~~~~~~~
 //change two
 }.bind(_this));

如果您使用的是 ES2015,为什么不使用 lambda(箭头函数)?他们自动绑定它

open(opts) {
  let modalOptions = {
    size: opts.size || '',
    templateUrl: 'modal.html',
    controller: function controller($scope, $uibModalInstance) {
      this._options = {
        id: opts.id
      };
      this.hcbuttons = [{
        id: '1',
        name: 'test'
      }, {
        id: '2',
        name: 'abc'
      }];
      publisher.subscribe('triggered', this._options.id, (event, creator) => {
        let result = this.hcbuttons.filter(obj => obj.id === creator)[0];
        if (result.sync) {
          console.log('disabledall');
        }
      });
    }
  }
}

在这里,您可以阅读有关箭头函数的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions 以及它们的工作原理(将来可能会对您有所帮助)。