2016-06-22 243 views
0

对不起,我不知道该怎么说这个问题..我知道这是某种范围问题..但是我正在努力完成不可能的事情?如何在构造函数中访问构造函数成员?

app.factory('SystemStatusConnectionFactory', ['$timeout', '$q', 'SystemStatusFactory', 'SystemStatusOptionsFactory', 
function ($timeout, $q, SystemStatusFactory, SystemStatusOptionsFactory) { 

    var self = this; 

    var SystemStatusConnectionFactory = function (ip, user, pw, options) { 
     this.data = { 
      count: 0 
     }; 

    this.PollIP = function() { 
     console.log(this.data.count); //WORKS 
     $timeout(function() { 
      console.log(self.data.count); //DOES NOT WORK 
      console.log(this.data.count); //DOES NOT WORK 
     }, 1000); 
    } 
    }; 
... etc 
+1

您把'self = this'放在错误的范围内。它应该进入构造函数。 – Bergi

+0

有一点适当的缩进将有助于识别这类问题。 – Bergi

+0

@Bergi叹了口气,工作。谢谢 – user1189352

回答

0

很难确切地知道发生了什么,而没有看到更多的代码。

如果你将它与你的函数绑定,你可以确保这个引用了你想要的任何上下文。

app.factory('SystemStatusConnectionFactory', ['$timeout', '$q', 'SystemStatusFactory', 'SystemStatusOptionsFactory', 
(function ($timeout, $q, SystemStatusFactory, SystemStatusOptionsFactory) { 

    var self = this; //this is now pointing to 'app' 

    var SystemStatusConnectionFactory = (function (ip, user, pw, options) { 

     this.data = { // this is now pointing to app as well. 
      count: 0 
     }; 

     this.PollIP = function() { 
      $timeout(function() { 
       console.log(self.data.count); // Self points to app. 
       console.log(this.data.count); // This points to the window object 
      }, 1000); 
     } 
    }).bind(this); 
}).bind(app) // Use bind to set app as the context of the function or 'this' 

**我让你想“这”指代的应用程序**

+0

谢谢你的描述。这在技术上是可行的,但只是简单地把var self = this放在构造函数中,就像Bergi提到的那样工作 – user1189352

+1

不,这个''从来不指向任何函数。 – Bergi

+0

是的,你是对的。我没有正确解释。我会编辑我的答案。 – Dan

1

不知道,如果你已经解决了这个从意见(因为我看不到的假设为什么不该” t工作在第一位),但你有没有试过在该超时的函数参数上使用bind()函数?这将消除使用的需要var self = this

// ... 
this.PollIP = function() { 
     console.log(this.data.count); 
     $timeout(function() { 
      console.log(self.data.count); 
      console.log(this.data.count); 
     }.bind(this), 1000); // modified line 
    } 
// ...