【问题标题】:angular acsess 'this' in callback [duplicate]回调中的角度访问“this”[重复]
【发布时间】:2016-03-22 22:47:19
【问题描述】:

我在我的 Angular 应用程序中的服务内存储了一个对象,我无法从回调方法中访问“this”。像这样的...

    app.service("myService", ['$http', '$q', 
        function($http, $q) {
            return ({foo: foo});

            this.myObj = {};

          function doSomething(param, callback){
            param++;
            callback(param);
          } 

          function foo(param){
          doSomething(param, function(responce){ 
            this.myObj.myParam = responce;//'this' is undefined
          });
          }
     });

如何正确访问它? 谢谢...

【问题讨论】:

  • 请在提出新问题之前使用搜索。
  • 下次会努力的更好...是的,比你好!

标签: javascript angularjs callback


【解决方案1】:

'this' 仅保留在函数的当前范围内。在新函数中调用时,“this”会发生变化。大多数人所做的是 var that = this;

 app.service("myService", ['$http', '$q', 
    function($http, $q) {
        var that = this;

        return ({foo: foo});

        this.myObj = {};

      function doSomething(param, callback){
        param++;
        callback(param);
      } 

      function foo(param){
        doSomething(param, function(responce){ 
          that.myObj.myParam = responce;//'that' defined
        });
      }
 });

【讨论】:

    【解决方案2】:

    如果obj是你想成为this的对象,你可以使用bind将它设置为函数f的实际this,例如:f.bind(obj)。

    来自documentation:

    bind() 方法创建一个新函数,在调用该函数时,会将其 this 关键字设置为提供的值 [...]

    【讨论】:

      【解决方案3】:

      您应该首先将“this”对象存储到某个变量中。 你应该在回调函数中使用它。

      app.service("myService", ['$http', '$q', 
          function($http, $q) {
              return ({foo: foo});
              var self = this;
              self.myObj = {};
      
            function doSomething(param, callback){
              param++;
              callback(param);
            } 
      
            function foo(param){
            doSomething(param, function(responce){ 
              self.myObj.myParam = responce;
            });
            }
       });
      

      希望对你有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-14
        • 1970-01-01
        • 2018-05-05
        • 2017-03-14
        • 2016-07-20
        • 2012-12-27
        • 2021-12-30
        相关资源
        最近更新 更多