2016-06-22 51 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 
    } 
// ...