[英]How can i access JavaScript constructor object as an IFFI function parameter?
[英]How can I access a constructor member within a constructor function?
抱歉,我不確定該如何措辭。.我知道這是某種范圍的問題..但是我要完成的工作是不可能的嗎?
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
不知道您是否已經從注釋中解決了這個問題(因為我首先不明白為什么不應該這樣做),但是您是否嘗試過對該超時的function參數使用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
}
// ...
在沒有看到更多代碼的情況下,很難確切知道發生了什么。
如果將其與函數綁定,則可以確保它指向您想要的任何上下文。
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'
**我假設您希望“此”指代應用**
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.